The NIF concept was introduced in R13B03 as an EXPERIMENTAL feature. The interfaces may be changed in any way in coming releases. The plan is however to lift the experimental label and maintain interface backward compatibility from R14B.
Incompatible changes in R13B04:
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!", ERL_NIF_LATIN1);
}
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
A NIF must be exported or used locally by the module (or both). An unused local stub function will be optimized away by the compiler causing loading of the NIF library to fail.
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 Erlang 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
private data can be set when the NIF library is loaded and
then retrieved by calling
There is 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 also be unloaded if it is replaced
by another version of the library by a second call to
All functions that a NIF library needs to do with Erlang are performed through the NIF API functions. There are functions for the following functionality:
Any Erlang terms can be passed to a NIF as function arguments and
be returned as function return values. The terms are of C-type
Terms of type binary are accessed with the help of the struct type
The raw data pointed to by
Binaries are sequences of whole bytes. Bitstrings with an arbitrary bit length have no support yet.
The use of resource objects is a way to return pointers to
native data structures from a NIF in a safe way. A resource object is
just a block of memory allocated with
All resource objects are created as instances of some resource type.
This makes resources from different modules to be distinguishable.
A resource type is created by calling
Resource types support upgrade in runtime by allowing a loaded NIF library to takeover an already existing resource type and thereby "inherit" all existing objects of that type. The destructor of the new library will thereafter be called for the inherited objects and the library with the old destructor function can be safely unloaded. Existing resource objects, of a module that is upgraded, must either be deleted or taken over by the new NIF library. The unloading of a library will be postponed as long as there exist resource objects with a destructor function in the library.
Here is a template example of how to create and return a resource object.
ERL_NIF_TERM term;
MyStruct* ptr = enif_alloc_resource(env, my_resource_type, sizeof(MyStruct));
/* initialize struct ... */
term = enif_make_resource(env, ptr);
if (keep_a_reference_of_our_own) {
/* store 'ptr' in static variable, private data or other resource object */
}
else {
enif_release_resource(env, obj);
/* resource now only owned by "Erlang" */
}
return term;
}
A NIF is thread-safe without any explicit synchronization as
long as it acts as a pure function and only reads the supplied
arguments. As soon as you write towards a shared state either through
static variables or
The library initialization callbacks
Avoid doing lengthy work in NIF calls as that may degrade the responsiveness of the VM. NIFs are called directly by the same scheduler thread that executed the calling Erlang code. The calling scheduler will thus be blocked from doing any other work until the NIF returns.
This is the magic macro to initialize a NIF library. It should be evaluated in global file scope.
The library will fail to load if
Works the same as
The library will fail to load if
Works the same as
The library will fail to load if
Variables of type
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.
typedef struct {
unsigned size;
unsigned char* data;
} ErlNifBinary;
Each instance of
typedef void ErlNifResourceDtor(ErlNifEnv* env, void* obj);
The function prototype of a resource destructor function. A destructor function is not allowed to call any term-making functions.
typedef enum {
ERL_NIF_LATIN1
}ErlNifCharEncoding;
The character encoding used in strings. The only supported
encoding is currently
Used by
Allocate memory of
Allocate a new binary of size
Return false if allocation failed.
Allocate a memory managed resource object of type
Return an integer less than, equal to, or greater than
zero if
Same as
Same as
Same as
Same as
Same as
Same as
Free memory allocated by
Write a null-terminated string, in the buffer pointed to by
Set
Set
Set
Set
Set
Set
Set
Return false if
Write a null-terminated string, in the buffer pointed to by
If
Return false if
Set
Set
Initialize the structure pointed to by
Initialize the structure pointed to by
Return true if
Return true if
Return true if
Return true if
Return true if the two terms are identical. Corresponds to the
Erlang operators
Return true if
Return true if
Return true if
Return true if
Return true if
Create an atom term from the C-string
Make a badarg exception to be returned from a NIF.
Make a binary term from
Create a floating-point term from a
Try to create the term of an already existing atom from
the C-string
Create an integer term.
Create an ordinary list term of length
Create an ordinary list term with length indicated by the
function name. Prefer these functions (macros) over the variadic
Create a list cell
Create an ordinary list containing the elements of array
Create an integer term from a
Allocate a binary of size
Return a pointer to the raw binary data and set
Create a reference like
Create an opaque handle to a memory managed resource object
obtained by
Note that the only defined behaviour of using a resource term in
an Erlang program is to store it and send it between processes on the
same node. Other operations such as matching or
Create a list containing the characters of the
null-terminated string
Make a subbinary of binary
Create a tuple term of arity
Create a tuple term with length indicated by the
function name. Prefer these functions (macros) over the variadic
Create a tuple containing the elements of array
Create an integer term from an
Create an integer term from an
Same as
Same as
Same as
Same as
Same as
Create or takeover a resource type identified by the string
The two flag values can be combined with bitwise-or. To avoid unintentional
name clashes a good practice is to include the module name as part of the
type
On success, return a pointer to the resource type and
Note that
Return the pointer to the private data that was set by
Was previously named
Change the size of a binary
Release a binary obtained
from
Release a resource object obtained from
Same as
Same as
Same as
Same as
Same as
Same as
Same as
Same as
Get the byte size of a resource object
Same as
Same as
Same as
Same as
Same as
Same as
Same as
Same as
Same as
Same as
Same as