3

I'm doing a C-Erlang integration using NIF and I'm having some trouble to initialize a Binary and add a char* pointing to its data.

I'm doing this way:

ErlNifBinary *output_binary;
enif_alloc_binary(500, output_binary);

strcpy(output_binary->data, "Here is a string");
return enif_make_binary(env, output_binary); 

Any ideas about what I'm not doing right? I'm getting a segmentation fault.

UPDATE: I get rid of the segmentation fault. But now I can't return a Erlang binary containing a String.

Using enif_make_string with the binary.data I get a String on Erlang. But when I try to use enif_make_binary with the binary, I get things like this <<0,0,0,0,0,0,0,0,112,40,129,20>> what do I need to do to convert?

Rodrigo Flores
  • 2,411
  • 18
  • 17

3 Answers3

0

For anyone who's looking for this, it's actually easy in C or C++.

You need to allocate the ErlNifBinary object (not the string). Once you have created the ERL_NIF_TERM through a call to enif_make_binary the ErlNifBinary becomes read-only and ownership is transferred to the ERL_NIF_TERM. You can effectively forget about the ErlNifBinary object.

ErlNifBinary bin;
std::string str = "hi there";

enif_alloc_binary(str.size(), &bin);

strcpy((char*)bin.data, str.c_str());
bin.size = str.size();

ERL_NIF_TERM term = enif_make_binary(env,&bin);

If you are working in pure C a static string works just as well.

ErlNifBinary bin;
const char * str = "hi there";

enif_alloc_binary(strlen(str), &bin);

strcpy((char*)bin.data, str);
bin.size = strlen(str);

ERL_NIF_TERM term = enif_make_binary(env,&bin);
GCUGreyArea
  • 141
  • 2
  • 7
0

You allocate memory for the output_binary object but output_binary->data points to an invalid object. You can allocate memory for output_binary->data this way:

output_binary->data = malloc(sizeof "Here is a string");  // or enif_alloc
strcpy(output_binary->data, "Here is a string");
ouah
  • 142,963
  • 15
  • 272
  • 331
0

Just found out the problem.

I was supposed to return the address of a binary not a binary so just a return enif_make_binary(env, &output_binary); make it work.

Rodrigo Flores
  • 2,411
  • 18
  • 17