20012009 Ericsson AB. All Rights Reserved. The contents of this file are subject to the Erlang Public License, Version 1.1, (the "License"); you may not use this file except in compliance with the License. You should have received a copy of the Erlang Public License along with this software. If not, it can be retrieved online at http://www.erlang.org/. Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. erl_nif Sverker Eriksson Sverker Eriksson 1 2009-11-17 PA1 erl_nif.xml
erl_nif API functions for an Erlang NIF library

The NIF concept was introduced in R13B03 as an EXPERIMENTAL feature. The interfaces may be changed in any way in coming releases. The API is still sparse and contains only the most basic functions to read and write Erlang terms.

R13B04: The function prototypes of the NIFs have changed to expect argc and argv arguments. The arity of a NIF is by that no longer limited to 3.

A NIF library contains native implementation of some functions of an erlang module. The native implemented functions (NIFs) are called like any other functions without any difference to the caller. Each NIF must also have an implementation in Erlang that will be invoked if the function is called before the NIF library has been successfully loaded. A typical such stub implementation is to throw an exception. But it can also be used as a fallback implementation if the NIF library is not implemented for some architecture.

A minimal example of a NIF library can look like this:

/* niftest.c */ #include "erl_nif.h" static ERL_NIF_TERM hello(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) { return enif_make_string(env, "Hello world!"); } static ErlNifFunc nif_funcs[] = { {"hello", 0, hello} }; ERL_NIF_INIT(niftest,nif_funcs,NULL,NULL,NULL,NULL)

and the erlang module would have to look something like this:

-module(niftest). -export([init/0, hello/0]). init() -> erlang:load_nif("./niftest", 0). hello() -> "NIF library not loaded".

and compile and test something like this (on Linux):

$> gcc -fPIC -shared -o niftest.so niftest.c -I $ERL_ROOT/usr/include/ $> erl 1> c(niftest). {ok,niftest} 2> niftest:hello(). "NIF library not loaded" 3> niftest:init(). ok 4> niftest:hello(). "Hello world!"

A better solution for a real module is to take advantage of the new directive on_load to automatically load the NIF library when the module is loaded.

A loaded NIF library is tied to the Erlang module code version that loaded it. If the module is upgraded with a new version, the new code will have to load its own NIF library (or maybe choose not to). The new code version can however choose to load the exact same NIF library as the old code if it wants to. Sharing the same dynamic library will mean that static data defined by the library will be shared as well. To avoid unintentionally shared static data, each Erlang module code can keep its own private data. This global private data can be set when the NIF library is loaded and then retrieved by calling enif_get_data().

There is currently no way to explicitly unload a NIF library. A library will be automatically unloaded when the module code that it belongs to is purged by the code server. A NIF library will can also be unloaded by replacing it with another version of the library by a second call to erlang:load_nif/2 from the same module code.

INITIALIZATION ERL_NIF_INIT(MODULE, ErlNifFunc funcs[], load, reload, upgrade, unload)

This is the magic macro to initialize a NIF library. It should be evaluated in global file scope.

MODULE is the name of the Erlang module as an identifier without string quotations. It will be stringified by the macro.

funcs is a static array of function descriptors for all the implemented NIFs in this library.

load, reload, upgrade and unload are pointers to functions. One of load, reload or upgrade will be called to initialize the library. unload is called to release the library. They are all described individually below.

int (*load)(ErlNifEnv* env, void** priv_data, ERL_NIF_TERM load_info)

load is called when the NIF library is loaded and there is no previously loaded library for this module.

*priv_data can be set to point to some private data that the library needs in able to keep a state between NIF calls. enif_get_data() will return this pointer.

load_info is the second argument to erlang:load_nif/2.

The library will fail to load if load returns anything other than 0. load can be NULL in case no initialization is needed.

int (*reload)(ErlNifEnv* env, void** priv_data, ERL_NIF_TERM load_info)

reload is called when the NIF library is loaded and there is already a previously loaded library for this module code.

Works the same as load. The only difference is that *priv_data already contains the value set by the previous call to load or reload.

The library will fail to load if reload returns anything other than 0 or if reload is NULL.

int (*upgrade)(ErlNifEnv* env, void** priv_data, void** old_priv_data, ERL_NIF_TERM load_info)

upgrade is called when the NIF library is loaded and there is no previously loaded library for this module code, BUT there is old code of this module with a loaded NIF library.

Works the same as load. The only difference is that *old_priv_data already contains the value set by the last call to load or reload for the old module code. It is allowed to write to both *priv_data and *old_priv_data.

The library will fail to load if upgrade returns anything other than 0 or if upgrade is NULL.

void (*unload)(ErlNifEnv* env, void* priv_data)

unload is called when the module code that the NIF library belongs to is purged as old. New code of the same module may or may not exist.

DATA TYPES ErlNifEnv

ErlNifEnv contains information about the context in which a NIF call is made. This pointer should not be dereferenced in any way, but only passed on to API functions. An ErlNifEnv pointer is only valid until the function, where is what supplied as argument, returns. There is thus useless and dangerous to store ErlNifEnv pointers in between NIF calls.

ErlNifFunc

typedef struct { const char* name; unsigned arity; ERL_NIF_TERM (*fptr)(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]); } ErlNifFunc;

Describes a NIF by its name, arity and implementation. fptr is a pointer to the function that implements the NIF. The argument argv of a NIF will contain the function arguments passed to the NIF and argc is the length of the array, i.e. the function arity. argv[N-1] will thus denote the Nth argument to the NIF. Note that the argc argument allows for the same C function to implement several Erlang functions with different arity (but same name probably).

ErlNifBinary

typedef struct { unsigned size; unsigned char* data; } ErlNifBinary;

ErlNifBinary contains transient information about an inspected binary term. data is a pointer to a buffer of size bytes with the raw content of the binary.

ERL_NIF_TERM

Variables of type ERL_NIF_TERM can refere to any Erlang term. This is an opaque type and values of it can only by used either as arguments to API functions or as return values from NIFs. A variable of type ERL_NIF_TERM is only valid until the NIF call, where it was obtained, returns.

void*enif_alloc(ErlNifEnv* env, size_t size) Allocate dynamic memory.

Allocate memory of size bytes. Return NULL if allocation failed.

intenif_alloc_binary(ErlNifEnv* env, unsigned size, ErlNifBinary* bin) Create a new binary.

Allocate a new binary of size of size bytes. Initialize the structure pointed to by bin to refer to the allocated binary. Return false if allocation failed.

intenif_compare(ErlNifEnv* env, ERL_NIF_TERM lhs, ERL_NIF_TERM rhs) Compare two terms

Return an integer less than, equal to, or greater than zero if lhs is found, respectively, to be less than, equal, or greater than rhs. Corresponds to the Erlang operators ==, /=, =<, <, >= and > (but not =:= or =/=).

voidenif_free(ErlNifEnv* env, void* ptr) Free dynamic memory

Free memory allocated by enif_alloc.

void*enif_get_data(ErlNifEnv* env) Get the private data of a NIF library

Return the pointer to the private data that was set by load, reload or upgrade.

intenif_get_double(ErlNifEnv* env, ERL_NIF_TERM term, double* dp) Read a floating-point number term.

Set *dp to the floating point value of term or return false if term is not a float.

intenif_get_int(ErlNifEnv* env, ERL_NIF_TERM term, int* ip) Read an integer term.

Set *ip to the integer value of term or return false if term is not an integer or is outside the bounds of type int

intenif_get_list_cell(ErlNifEnv* env, ERL_NIF_TERM list, ERL_NIF_TERM* head, ERL_NIF_TERM* tail) Get head and tail from a list

Set *head and *tail from list or return false if list is not a non-empty list.

intenif_get_tuple(ErlNifEnv* env, ERL_NIF_TERM term, int* arity, const ERL_NIF_TERM** array) Inspect the elements of a tuple.

If term is a tuple, set *array to point to an array containing the elements of the tuple and set *arity to the number of elements. Note that the array is read-only an (*array)[N-1] will be the Nth element of the tuple. *array is undefined if the arity of the tuple is zero.

Return false if term is not a tuple.

intenif_get_ulong(ErlNifEnv* env, ERL_NIF_TERM term, unsigned long* ip) Read an unsigned integer term.

Set *ip to the unsigned long integer value of term or return false if term is not an unsigned integer or is outside the bounds of type unsigned long

intenif_inspect_binary(ErlNifEnv* env, ERL_NIF_TERM bin_term, ErlNifBinary* bin) Inspect the content of a binary

Initialize the structure pointed to by bin with transient information about the binary term bin_term. Return false if bin_term is not a binary.

intenif_is_atom(ErlNifEnv* env, ERL_NIF_TERM term) Determine if a term is an atom

Return true if term is an atom.

intenif_is_binary(ErlNifEnv* env, ERL_NIF_TERM term) Determine if a term is a binary

Return true if term is a binary

intenif_is_identical(ErlNifEnv* env, ERL_NIF_TERM lhs, ERL_NIF_TERM rhs) Erlang operator =:=

Return true if and only if the two terms are identical. Corresponds to the Erlang operators =:= and =/=.

intenif_is_ref(ErlNifEnv* env, ERL_NIF_TERM term) Determine if a term is a reference

Return true if term is a reference.

ERL_NIF_TERMenif_make_atom(ErlNifEnv* env, const char* name) Create an atom term

Create an atom term from the C-string name. Atom terms may be saved and used between NIF calls.

ERL_NIF_TERMenif_make_badarg(ErlNifEnv* env) Make a badarg exception.

Make a badarg exception to be returned from a NIF.

ERL_NIF_TERMenif_make_binary(ErlNifEnv* env, ErlNifBinary* bin) Make a binary term.

Make a binary term from bin. Will also release the binary.

ERL_NIF_TERMenif_make_double(ErlNifEnv* env, double d) Create an floating-point term

Create an floating-point term from a double.

intenif_make_existing_atom(ErlNifEnv* env, const char* name, ERL_NIF_TERM* atom) Create an existing atom term

Try to create the term of an already existing atom from the C-string name. If the atom already exist store the term in *atom and return true, otherwise return false.

ERL_NIF_TERMenif_make_int(ErlNifEnv* env, int i) Create an integer term

Create an integer term.

ERL_NIF_TERMenif_make_list(ErlNifEnv* env, unsigned cnt, ...) Create a list term.

Create an ordinary list term of length cnt. Expects cnt number of arguments (after cnt) of type ERL_NIF_TERM as the elements of the list. An empty list is returned if cnt is 0.

ERL_NIF_TERMenif_make_list_cell(ErlNifEnv* env, ERL_NIF_TERM head, ERL_NIF_TERM tail) Create a list cell.

Create a list cell [head | tail].

ERL_NIF_TERMenif_make_ref(ErlNifEnv* env) Create a reference.

Create a reference like erlang:make_ref/0.

ERL_NIF_TERMenif_make_string(ErlNifEnv* env, const char* string) Create a string.

Create a list containing the characters of the C-string string.

ERL_NIF_TERMenif_make_tuple(ErlNifEnv* env, unsigned cnt, ...) Create a tuple term.

Create a tuple term of arity cnt. Expects cnt number of arguments (after cnt) of type ERL_NIF_TERM as the elements of the tuple.

ERL_NIF_TERMenif_make_ulong(ErlNifEnv* env, unsigned long i) Create an integer term from an unsigned long int

Create an integer term from an unsigned long int.

voidenif_release_binary(ErlNifEnv* env, ErlNifBinary* bin) Release a binary.

Release a binary obtained from enif_alloc_binary or enif_inspect_binary.

SEE ALSO

load_nif(3)