More elegant way to

Previous Topic Next Topic
 
classic Classic list List threaded Threaded
2 messages Options
Reply | Threaded
Open this post in threaded view
|

More elegant way to

Damien Towning
Hi everyone, 

I have some c code using c_node that I have successfully got working with Erlang ( through Elixir ) and I am wondering if on the C side a more elegant way exists to pass data back to the Erlang/Elixir than what I am currently doing.  My C code looks a bit like this.

 else if (erl_match(msg_pattern_b, emsg->msg)) {  
    ETERM *term = erl_var_content(msg_pattern_b, "Term");
    response = erl_format("{ok, ~w}",erl_mk_string(floats_as_string()));   
    erl_free_term(term);
  }

 I've parsed a series of floats in to a char * and then passed that back to erl_mk_string().

I hope I have framed this question in a way that makes sense. I'd like to take a list of floating point values directly and pass it directly back to my calling Elixir code as a list without having to parse it in and out of a string. 

Is this possible. I have spent quite a bit of time now digging through the erl_ documentation and trying to find an example but I just can't quite see it. 

Thanks !  




_______________________________________________
erlang-questions mailing list
[hidden email]
http://erlang.org/mailman/listinfo/erlang-questions
Reply | Threaded
Open this post in threaded view
|

Re: More elegant way to

Nathaniel Waisbrot
>  else if (erl_match(msg_pattern_b, emsg->msg)) {  
>     ETERM *term = erl_var_content(msg_pattern_b, "Term");
>     response = erl_format("{ok, ~w}",erl_mk_string(floats_as_string()));  
>     erl_free_term(term);
>   }
>


Your sample code looks either buggy or incomplete (you create `term` and then call `erl_free_term` on it without ever using it).

If understand your question, you want to return (e.g.) `{ok, [1.0, 1.1, 1.2, 2.0]}`. Right now you're returning something like `{ok, "[1.0, 1.1, 1.2, 2.0]"}` and then parsing the values out of the char-list in BEAM-land?

How about (untested)

```
ETERM* floats_to_list(float clist[], size_t length) {
  ETERM* elist[length];
  unsigned i;
  for (i = 0; i < length; i++) {
    elist[i] = erl_mk_float(clist[i]);
  }
  return erl_mk_list(elist, length);
}

void top_function() {
  float *list_of_floats;
  size_t size_of_list;
  ETERM *response;
  // ...
  // somehow get these values loaded
  // ...
  response = floats_to_list(list_of_floats, size_of_list);
  send_response(response);
  // ...
}
```

_______________________________________________
erlang-questions mailing list
[hidden email]
http://erlang.org/mailman/listinfo/erlang-questions