Pregunta

When writing an Erlang C NIF, how can a pointer, created in C let's say an array, be returned to Erlang for later use by the same Erlang process in another NIF call?

 #define LENGTH = 50;

 int *a, array[LENGTH];

 a = enif_alloc(LENGTH * sizeof(int));

It should be a pointer that can be returned or even stored so that when I return to the NIF from within the same Erlang process I can access the pointer and the memory referenced by it.

¿Fue útil?

Solución

In this particular case, I would use enif_alloc_resource. Create a struct to contain your pointer and establish it as a resource object.

You could also encode it as a binary, but I would recommend against that, as it would allow erlang functions to modify the contents before passing it back in. Resource types are opaque from the erlang side and cannot be modified.

Otros consejos

To return binaries from a Nif I use enif_alloc_binary and enif_make_binary. Then in the Nif that will access the pointer pass in the binary and use enif_inspect_binary on the argument to get your ErlNifBinary which will contain the pointer to the data.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top