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?
3条答案
按热度按时间yvfmudvl1#
您为
output_binary
对象分配内存,但output_binary->data
指向无效对象。您可以按以下方式为output_binary->data
分配内存:slwdgvem2#
才发现了问题所在。
我应该返回二进制文件的地址,而不是二进制文件,所以只要一个
return enif_make_binary(env, &output_binary);
就可以了。acruukt93#
对于任何想知道这一点的人来说,在C或C++中这实际上很容易。
您需要分配
ErlNifBinary
对象(而不是字符串)。一旦您通过调用enif_make_binary
创建了ERL_NIF_TERM
,ErlNifBinary
将变为只读,所有权将转移到ERL_NIF_TERM
。您可以有效地忽略ErlNifBinary
对象。如果你是在纯C中工作,静态字符串也同样有效。