Search code examples
cpointerserlangerlang-nif

Return Pointer from Erlang C NIF


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.


Solution

  • 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.