'How to use binary strings in Elixir NIF

How do I get the char* data from an ERL_NIF_TERM coming from an Elixir binary string?

I see term_to_binary/1 function but it does not seem to be the right thing.



Solution 1:[1]

As it’s stated in NIF documentation

Terms of type binary are accessed with the help of struct type ErlNifBinary, which contains a pointer (data) to the raw binary data and the length (size) of the data in bytes. Both data and size are read-only and are only to be written using calls to API functions. Instances of ErlNifBinary are, however, always allocated by the user (usually as local variables).

That said, your NIF function should have a signature alongside

static ERL_NIF_TERM
foo(ErlNifEnv *env, int argc, const ERL_NIF_TERM argv[])

where argc is supposed to be 1, argv[0] would be a constant pointer to ErlNifBinary and the respective call would be like

def foo(binary), do: :erlang.nif_error("Load NIF!")

Solution 2:[2]

While using NIF, you have to use charlist and NOT Elixir binary Strings. Use to_charlist/1 function to convert binary string to charlist and then call the NIF function.

In the NIF function, you can read charlist like so,

#define MAXBUFLEN 1024

char src[MAXBUFLEN];
enif_get_string(env, argv[0], src, MAXBUFLEN, ERL_NIF_LATIN1);

src now holds the string value.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Aleksei Matiushkin
Solution 2 Hari Roshan