Passing BIGINT between Erlang VM and the NIFs

233 views Asked by At

Is there an efficient way to pass BIGINT (integers exceeding 64 bits for x86_64/amd64 architectures) between Erlang VM and the NIFs? So far I haven't found a supporting function in the enif module. Maybe converting BIGINTs to binaries will help, but there might be another good way.

1

There are 1 answers

1
Dogbert On

This post from 2011 says there wasn't any support for big integers in the NIF API at the time. I couldn't find any such function in Erlang/OTP 21's documentation, so the statement is likely true as of today as well.

Here's how you could pass a big integer as an array of bytes:

From Erlang, instead of passing the integer directly, pass two values: the sign of the integer and the binary obtained by calling binary:encode_unsigned/1 on the integer.

Integer = ...,
my_nif_function(Integer < 0, binary:encode_unsigned(Integer)).

In the NIF function, you can get access to the bytes of the second argument using enif_inspect_binary:

ErlNifBinary bin;
enif_inspect_binary(env, bin_term, &bin); // make sure to check the return value of this function in the real code

bin.data now points to bin.size bytes, representing the bytes of the integer in Big Endian order (if you want Little Endian, pass little as the second argument to binary:encode_unsigned/2 above).