通过NIF创建Erlang二进制文件,其中数据指向char *

toe95027  于 2022-12-08  发布在  Erlang
关注(0)|答案(3)|浏览(176)

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?

yvfmudvl

yvfmudvl1#

您为output_binary对象分配内存,但output_binary->data指向无效对象。您可以按以下方式为output_binary->data分配内存:

output_binary->data = malloc(sizeof "Here is a string");  // or enif_alloc
strcpy(output_binary->data, "Here is a string");
slwdgvem

slwdgvem2#

才发现了问题所在。
我应该返回二进制文件的地址,而不是二进制文件,所以只要一个return enif_make_binary(env, &output_binary);就可以了。

acruukt9

acruukt93#

对于任何想知道这一点的人来说,在C或C++中这实际上很容易。
您需要分配ErlNifBinary对象(而不是字符串)。一旦您通过调用enif_make_binary创建了ERL_NIF_TERMErlNifBinary将变为只读,所有权将转移到ERL_NIF_TERM。您可以有效地忽略ErlNifBinary对象。

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);

如果你是在纯C中工作,静态字符串也同样有效。

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);

相关问题