erl_nif(3)
โจ erl_nif(3) โ Erlang Module Definition โจ
๐ NAME
erl_nif โ API functions for an Erlang NIF library. periodt ๐
๐ฆ DESCRIPTION
A NIF library is where you put native implementations of some functions from an Erlang module. The native implemented functions (NIFs) get called just like any other function โ the caller literally cannot tell the difference. A NIF library is built as a dynamically linked library file and loaded at runtime by calling erlang:load_nif/2. slay โจ
โ ๏ธ WARNING: Use this functionality with extreme care. A native function is executed as a direct extension of the native code of the VM. Execution is not made in a safe environment. The VM cannot provide the same services as provided when executing Erlang code, such as pre-emptive scheduling or memory protection. If the native function does not behave well, the whole VM will misbehave. ๐
- A native function that crashes will crash the whole VM. ๐ญ
- An erroneously implemented native function can cause a VM internal state inconsistency, which can cause a crash of the VM, or miscellaneous misbehaviors of the VM at any point after the call to the native function. ๐ตโ๐ซ
- A native function doing lengthy work before returning degrades responsiveness of the VM, and can cause miscellaneous strange behaviors. Such strange behaviors include, but are not limited to, extreme memory usage, and bad load balancing between schedulers. Strange behaviors that can occur because of lengthy work can also vary between Erlang/OTP releases. ๐
๐ Example
A minimal example of a NIF library can look as follows:
/* 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)
The Erlang module can look as follows:
-module(niftest).
-export([init/0, hello/0]).
-nifs([hello/0]).
-on_load(init/0).
init() ->
erlang:load_nif("./niftest", 0).
hello() ->
erlang:nif_error("NIF library not loaded").
Compile and test can look as follows (on Linux):
$> gcc -fPIC -shared -o niftest.so niftest.c -I $ERL_ROOT/usr/include/
$> erl
1> c(niftest).
{ok,niftest}
2> niftest:hello().
"Hello world!"
In the example above the on_load directive is used to get function init called automatically when the module is loaded. Function init in turn calls erlang:load_nif/2, which loads the NIF library and replaces the hello function with its native implementation in C. Once loaded, a NIF library is persistent. It will not be unloaded until the module instance that it belongs to is purged. ๐
The -nifs() attribute specifies which functions in the module that are to be replaced by NIFs.
Each NIF must have an implementation in Erlang to be invoked if the function is called before the NIF library is successfully loaded. A typical such stub implementation is to call erlang:nif_error, which will raise an exception. The Erlang function can also be used as a fallback implementation if the NIF library lacks implementation for some OS or hardware architecture, for example. ๐
๐ NOTE: A NIF does not have to be exported, it can be local to the module. However, unused local stub functions will be optimized away by the compiler, causing loading of the NIF library to fail. ๐ฑ
๐ Functionality
All interaction between NIF code and the Erlang runtime system is performed by calling NIF API functions. Functions exist for the following functionality:
๐ Read and write Erlang terms
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 ERL_NIF_TERM and can only be read or written using API functions. Most functions to read the content of a term are prefixed enif_get_ and usually return true (or false) if the term is of the expected type (or not). The functions to write terms are all prefixed enif_make_ and usually return the created ERL_NIF_TERM. There are also some functions to query terms, like enif_is_atom, enif_is_identical, and enif_compare.
All terms of type ERL_NIF_TERM belong to an environment of type ErlNifEnv, except atoms created during loading (by callbacks load or upgrade). The lifetime of a term is controlled by the lifetime of its environment object. All API functions that read or write terms have the environment that the term belongs to as the first function argument. However, the atoms created during loading can be referred as a term in any ErlNifEnv. That is, the best practice is to create all your atoms during loading and store them in static/global variables, for example:
#include <erl_nif.h>
ERL_NIF_TERM world_atom;
static int load(ErlNifEnv* env, void** priv_data, ERL_NIF_TERM load_info)
{
world_atom = enif_make_atom(env, "world");
return 0;
}
static ERL_NIF_TERM hello(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
{
ERL_NIF_TERM hello_string = enif_make_string(env, "Hello", ERL_NIF_LATIN1);
return enif_make_tuple2(env, hello_string, world_atom);
}
static ErlNifFunc nif_funcs[] = { { "hello", 0, hello } };
ERL_NIF_INIT(niftest, nif_funcs, load, NULL, NULL, NULL)
๐งฌ Binaries
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). ๐พ
The raw data pointed to by data is only mutable after a call to enif_alloc_binary or enif_realloc_binary. All other functions that operate on a binary leave the data as read-only. A mutable binary must in the end either be freed with enif_release_binary or made read-only by transferring it to an Erlang term with enif_make_binary. However, it does not have to occur in the same NIF call. Read-only binaries do not have to be released. ๐
enif_make_new_binary can be used as a shortcut to allocate and return a binary in the same NIF call.
Binaries are sequences of whole bytes. Bitstrings with an arbitrary bit length have no support yet. ๐ง
๐ Resource objects
The use of resource objects is a safe way to return pointers to native data structures from a NIF. A resource object is only a block of memory allocated with enif_alloc_resource. A handle ("safe pointer") to this memory block can then be returned to Erlang by the use of enif_make_resource. The term returned by enif_make_resource is opaque in nature. It can be stored and passed between processes, but the only real end usage is to pass it back as an argument to a NIF. The NIF can then call enif_get_resource and get back a pointer to the memory block, which is guaranteed to still be valid. A resource object is not deallocated until the last handle term is garbage collected by the VM and the resource is released with enif_release_resource (not necessarily in that order). ๐ซถ
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 enif_open_resource_type when a library is loaded. Objects of that resource type can then later be allocated and enif_get_resource verifies that the resource is of the expected type. A resource type can have a user-supplied destructor function, which is automatically called when resources of that type are released (by either the garbage collector or enif_release_resource). Resource types are uniquely identified by a supplied name string and the name of the implementing module. ๐
The following is a template example of how to create and return a resource object.
ERL_NIF_TERM term;
MyStruct* obj = enif_alloc_resource(my_resource_type, sizeof(MyStruct));
/* initialize struct ... */
term = enif_make_resource(env, obj);
if (keep_a_reference_of_our_own) {
/* store 'obj' in static variable, private data or other resource object */
}
else {
enif_release_resource(obj);
/* resource now only owned by "Erlang" */
}
return term;
Notice that once enif_make_resource creates the term to return to Erlang, the code can choose to either keep its own native pointer to the allocated struct and release it later, or release it immediately and rely only on the garbage collector to deallocate the resource object eventually when it collects the term. ๐ง
Another use of resource objects is to create binary terms with user-defined memory management. enif_make_resource_binary creates a binary term that is connected to a resource object. The destructor of the resource is called when the binary is garbage collected, at which time the binary data can be released. An example of this can be a binary term consisting of data from a mmap'ed file. The destructor can then do munmap to release the memory region. ๐บ๏ธ
Resource types support upgrade in runtime by allowing a loaded NIF library to take over an already existing resource type and by that "inherit" all existing objects of that type. The destructor of the new library is thereafter 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 is postponed as long as there exist resource objects with a destructor function in the library. โป๏ธ
๐ Module upgrade and static data ๐
okay so bestie, here's the tea: a loaded NIF library is tied to the Erlang module instance that loaded it. that's the whole vibe. so when the module gets upgraded, the new module instance needs to load its own NIF library โ or maybe choose not to, no pressure, we support that decision ๐ .
but here's the fun part: the new module instance can, however, choose to load the exact same NIF library as the old code if it wants to. and sharing the dynamic library means that static data defined by the library is shared as well. so to avoid unintentionally shared static data between module instances, each Erlang module version can keep its own private data. this private data can be set when the NIF library is loaded, and later retrieved by calling enif_priv_data. iconic behavior fr fr โจ
๐งต Threads and concurrency ๐งต
A NIF is thread-safe without any explicit synchronization, as long as it acts as a pure function and only reads the supplied arguments. so chill, so demure ๐ซถ
but the second you write to a shared state โ either through static variables or through enif_priv_data โ you need to supply your own explicit synchronization. sorry bestie, no shortcuts. this includes terms in process independent environments that are shared between threads. and Resource objects also require synchronization if you treat them as mutable. lowkey important ngl.
also the library initialization callbacks load and upgrade are thread-safe even for shared state data. slay ๐
๐ Version Management ๐
When a NIF library is built, information about the NIF API version is compiled into the library. Then when a NIF library is loaded, the runtime system verifies that the library is of a compatible version.
erl_nif.h defines the following:
ERL_NIF_MAJOR_VERSIONโ Incremented when NIF library incompatible changes are made to the Erlang runtime system. Normally it suffices to recompile the NIF library when theERL_NIF_MAJOR_VERSIONhas changed, but it can, under rare circumstances, mean that NIF libraries must be slightly modified. If so, this will of course be documented.ERL_NIF_MINOR_VERSIONโ Incremented when new features are added. The runtime system uses the minor version to determine what features to use.
The runtime system normally refuses to load a NIF library if the major versions differ, or if the major versions are equal and the minor version used by the NIF library is greater than the one used by the runtime system. ngl that's a vibe check it will absolutely fail ๐
Old NIF libraries with lower major versions are, however, allowed after a bump of the major version during a transition period of two major releases. Such old NIF libraries can however fail if deprecated features are used. โ ๏ธ so like, proceed with caution bestie.
โฐ Time Measurement โฐ
Support for time measurement in NIF libraries:
ErlNifTimeErlNifTimeUnitenif_monotonic_time()enif_time_offset()enif_convert_time_unit()
๐ฎ I/O Queues ๐ฎ
The Erlang nif library contains function for easily working with I/O vectors as used by the unix system call writev. The I/O Queue is not thread safe, so some other synchronization mechanism has to be used. ma'am, handle that yourself ๐ญ
SysIOVecErlNifIOVecenif_ioq_create()enif_ioq_destroy()enif_ioq_enq_binary()enif_ioq_enqv()enif_ioq_deq()enif_ioq_peek()enif_ioq_peek_head()enif_inspect_iovec()enif_free_iovec()
Typical usage when writing to a file descriptor looks like this:
int writeiovec(ErlNifEnv *env, ERL_NIF_TERM term, ERL_NIF_TERM *tail,
ErlNifIOQueue *q, int fd) {
ErlNifIOVec vec, *iovec = &vec;
SysIOVec *sysiovec;
int saved_errno;
int iovcnt, n;
if (!enif_inspect_iovec(env, 64, term, tail, &iovec))
return -2;
if (enif_ioq_size(q) > 0) {
/* If the I/O queue contains data we enqueue the iovec and
then peek the data to write out of the queue. */
if (!enif_ioq_enqv(q, iovec, 0))
return -3;
sysiovec = enif_ioq_peek(q, &iovcnt);
} else {
/* If the I/O queue is empty we skip the trip through it. */
iovcnt = iovec->iovcnt;
sysiovec = iovec->iov;
}
/* Attempt to write the data */
n = writev(fd, sysiovec, iovcnt);
saved_errno = errno;
if (enif_ioq_size(q) == 0) {
/* If the I/O queue was initially empty we enqueue any
remaining data into the queue for writing later. */
if (n >= 0 && !enif_ioq_enqv(q, iovec, n))
return -3;
} else {
/* Dequeue any data that was written from the queue. */
if (n > 0 && !enif_ioq_deq(q, n, NULL))
return -4;
}
/* return n, which is either number of bytes written or -1 if
some error happened */
errno = saved_errno;
return n;
}
๐ Long-running NIFs ๐
As mentioned in the warning text at the beginning of this manual page, it is of vital importance that a native function returns relatively fast. it's difficult to give an exact maximum amount of time that a native function is allowed to work, but usually a well-behaving native function is to return to its caller within 1 millisecond. so like... one millisecond. that's the vibe check.
This can be achieved using different approaches. If you have full control over the code to execute in the native function, the best approach is to divide the work into multiple chunks of work and call the native function multiple times. This is, however, not always possible, for example when calling third-party libraries. rip.
The enif_consume_timeslice() function can be used to inform the runtime system about the length of the NIF call. It is typically always to be used unless the NIF executes very fast. periodt.
If the NIF call is too lengthy, this must be handled in one of the following ways to avoid degraded responsiveness, scheduler load balancing problems, and other strange behaviors:
โ๏ธ Yielding NIF โ๏ธ
If the functionality of a long-running NIF can be split so that its work can be achieved through a series of shorter NIF calls, the application has two options:
- Make that series of NIF calls from the Erlang level.
- Call a NIF that first performs a chunk of the work, then invokes the
enif_schedule_niffunction to schedule another NIF call to perform the next chunk. The final call scheduled in this manner can then return the overall result.
Breaking up a long-running function in this manner enables the VM to regain control between calls to the NIFs. that's the dream ๐ฆ
This approach is always preferred over the other alternatives described below. This both from a performance perspective and a system characteristics perspective. no debate, this is the main character energy ๐
๐งต Threaded NIF ๐งต
This is accomplished by dispatching the work to another thread managed by the NIF library, return from the NIF, and wait for the result. The thread can send the result back to the Erlang process using enif_send. Information about thread primitives is provided below.
๐ Dirty NIF ๐
A NIF that cannot be split and cannot execute in a millisecond or less is called a "dirty NIF", as it performs work that the ordinary schedulers of the Erlang runtime system cannot handle cleanly. not the word "dirty" being the technical term ๐ญ but ok.
Applications that make use of such functions must indicate to the runtime that the functions are dirty so they can be handled specially. This is handled by executing dirty jobs on a separate set of schedulers called dirty schedulers. A dirty NIF executing on a dirty scheduler does not have the same duration restriction as a normal NIF. so at least there's that ๐
It is important to classify the dirty job correct. An I/O bound job should be classified as such, and a CPU bound job should be classified as such. If you should classify CPU bound jobs as I/O bound jobs, dirty I/O schedulers might starve ordinary schedulers. ๐ฑ starving schedulers is not the move. I/O bound jobs are expected to either block waiting for I/O, and/or spend a limited amount of time moving data.
To schedule a dirty NIF for execution, the application has two options:
- Set the appropriate flags value for the dirty NIF in its
ErlNifFuncentry. - Call
enif_schedule_nif, pass to it a pointer to the dirty NIF to be executed, and indicate with argumentflagswhether it expects the operation to be CPU-bound or I/O-bound.
A job that alternates between I/O bound and CPU bound can be reclassified and rescheduled using enif_schedule_nif so that it executes on the correct type of dirty scheduler at all times. For more information see the documentation of the erl command line arguments +SDcpu, and +SDio. iykyk โจ
While a process executes a dirty NIF, some operations that communicate with it can take a very long time to complete. Suspend or garbage collection of a process executing a dirty NIF cannot be done until the dirty NIF has returned. Thus, other processes waiting for such operations to complete might have to wait for a very long time. ๐ brutal.
Blocking multi-scheduling, that is, calling erlang:system_flag(multi_scheduling, block), can also take a very long time to complete. This is because all ongoing dirty operations on all dirty schedulers must complete before the block operation can complete.
Many operations communicating with a process executing a dirty NIF can, however, complete while it executes the dirty NIF. For example, retrieving information about it through process_info, setting its group leader, register/unregister its name, and so on. oh periodt, we love a partial win ๐ธ
so the process is basically ghosting ๐ โ termination of a process executing a dirty NIF can only be completed up to a certain point while it executes that dirty NIF. Like, the Erlang side of things wraps up: all Erlang resources, such as its registered name and its ETS tables, are released. All links and monitors are triggered. But the execution of the NIF itself? not stopped. The NIF can safely continue execution, allocate heap memory, and so on, but bestie it is of course better to stop executing as soon as possible. ๐
The NIF can check whether a current process is alive using enif_is_current_process_alive. Communication using enif_send and enif_port_command is also dropped when the sending process is not alive. Deallocation of certain internal resources, such as process heap and process control block, is delayed until the dirty NIF has completed.
โจ Initialization โจ ๐ง
ERL_NIF_INIT(MODULE, ErlNifFunc funcs[], load, NULL, upgrade, unload)
This is the magic macro that initializes a NIF library. It is to be evaluated in global file scope โ no hiding it inside a function, okay? ๐
- MODULE is the name of the Erlang module as an identifier without string quotations. It is stringified by the macro.
funcsis a static array of function descriptors for all the implemented NIFs in this library.load,upgradeandunloadare pointers to functions. One ofloadorupgradeis called to initialize the library.unloadis called to release the library. All are described individually below. ๐
The fourth argument NULL is ignored. It was earlier used for the deprecated reload callback which is no longer supported since OTP 20.
If compiling a NIF lib for static inclusion through --enable-static-nifs, then the macro STATIC_ERLANG_NIF_LIBNAME must be defined as the name of the archive file (excluding file extension .a) without string quotations. It must only contain characters allowed in a C indentifier. The macro must be defined before erl_nif.h is included. If the older macro STATIC_ERLANG_NIF is instead used, then the name of the archive file must match the name of the module.
Multiple static NIF libraries can be included in a single archive file by specifying the respective STATIC_ERLANG_NIF_LIBNAME values in the configure call separated by colons after the archive file name:
int (*load)(ErlNifEnv* caller_env, void** priv_data, ERL_NIF_TERM load_info)
load is called when the NIF library is loaded and no previously loaded library exists for this module. ๐
*priv_data can be set to point to some private data if the library needs to keep a state between NIF calls. enif_priv_data returns this pointer. *priv_data is initialized to NULL when load is called.
load_info is the second argument to erlang:load_nif/2.
The library fails to load if load returns anything other than 0. load can be NULL if initialization is not needed.
int (*upgrade)(ErlNifEnv* caller_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 old code of this module with a loaded NIF library. ๐ฆ
Works as load, except that *old_priv_data already contains the value set by the last call to load or upgrade for the old module instance. *priv_data is initialized to NULL when upgrade is called. It is allowed to write to both *priv_data and *old_priv_data. โ๏ธ
The library fails to load if upgrade returns anything other than 0 or if upgrade is NULL.
void (*unload)(ErlNifEnv* caller_env, void* priv_data)
unload is called when the module instance that the NIF library belongs to is purged as old. New code of the same module may or may not exist. ๐
๐ Data Types ๐
ERL_NIF_TERM
Variables of type ERL_NIF_TERM can refer 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. All ERL_NIF_TERMs belong to an environment (ErlNifEnv). A term cannot be destructed individually, it is valid until its environment is destructed.
ErlNifEnv
ErlNifEnv represents an environment that can host Erlang terms. All terms in an environment are valid as long as the environment is valid. ErlNifEnv is an opaque type; pointers to it can only be passed on to API functions. Three types of environments exist:
- Process bound environment โ Passed as the first argument to all NIFs. All function arguments passed to a NIF belong to that environment. The return value from a NIF must also be a term belonging to the same environment.
A process bound environment contains transient information about the calling Erlang process. The environment is only valid in the thread where it was supplied as argument until the NIF returns. It is thus useless and dangerous to store pointers to process bound environments between NIF calls. ๐ญ
- Callback environment โ Passed as the first argument to all the non-NIF callback functions (
load,upgrade,unload,dtor,down,stopanddyncall). Works like a process bound environment but with a temporary pseudo process that "terminates" when the callback has returned. Terms may be created in this environment but they will only be accessible during the callback. - Process independent environment โ Created by calling
enif_alloc_env. This environment can be used to store terms between NIF calls and to send terms withenif_send. A process independent environment with all its terms is valid until you explicitly invalidate it withenif_free_envorenif_send.
All contained terms of a list/tuple/map must belong to the same environment as the list/tuple/map itself. Terms can be copied between environments with enif_make_copy.
ErlNifFunc
typedef struct {
const char* name;
unsigned arity;
ERL_NIF_TERM (*fptr)(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]);
unsigned flags;
} ErlNifFunc;
Describes a NIF by its name, arity, and implementation. ๐ซถ
fptrโ A pointer to the function that implements the NIF.argvโ Contains the function arguments passed to the NIF.argcโ The array length, that is, the function arity.argv[N-1]thus denotes the Nth argument to the NIF. Notice that the argumentargcallows for the same C function to implement several Erlang functions with different arity (but probably with the same name). ๐คฏflagsโ Is0for a regular NIF (and so its value can be omitted for statically initializedErlNifFuncinstances).
flags can be used to indicate that the NIF is a dirty NIF that is to be executed on a dirty scheduler thread.
If the dirty NIF is expected to be CPU-bound, its flags field is to be set to ERL_NIF_DIRTY_JOB_CPU_BOUND. If it's expected to be I/O-bound set flags to ERL_NIF_DIRTY_JOB_IO_BOUND.
ErlNifBinary
typedef struct {
size_t 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.
Notice that ErlNifBinary is a semi-opaque type and you are only allowed to read fields size and data. ๐
ErlNifBinaryToTerm
An enumeration of the options that can be specified to enif_binary_to_term. For default behavior, use value 0.
When receiving data from untrusted sources, use option ERL_NIF_BIN2TERM_SAFE. ๐ก๏ธ
ErlNifMonitor
This is an opaque data type that identifies a monitor.
The nif writer is to provide the memory for storing the monitor when calling enif_monitor_process. The address of the data is not stored by the runtime system, so ErlNifMonitor can be used as any other data, it can be copied, moved in memory, forgotten, and so on. To compare two monitors, enif_compare_monitors must be used.
ErlNifOnHaltCallback
typedef void ErlNifOnHaltCallback(void *priv_data);
The function prototype of an on halt callback function.
An on halt callback can be installed using enif_set_option(). Such an installed callback will be called when the runtime system is halting. ๐ธ
ErlNifOnUnloadThreadCallback
typedef void ErlNifOnUnloadThreadCallback(void *priv_data);
The function prototype of an on_unload_thread callback function.
An on_unload_thread callback can be installed using enif_set_option(). Such an installed callback will be called by each scheduler thread when this module instance is purged.
ErlNifOption
An enumeration of the options that can be set using enif_set_option().
Currently valid options: ๐
ERL_NIF_OPT_DELAY_HALTโ Enable delay of runtime system halt with flushing enabled until all calls to NIFs in the NIF library have returned.ERL_NIF_OPT_ON_HALTโ Install a callback that will be called when the runtime system halts with flushing enabled.ERL_NIF_OPT_ON_UNLOAD_THREADโ Install a callback that will be called by each scheduler thread when the module instance that the NIF library belongs to is purged as old.
ErlNifPid
A process identifier (pid). In contrast to pid terms (instances of ERL_NIF_TERM), ErlNifPids are self-contained and not bound to any environment. ErlNifPid is an opaque type. It can be copied, moved in memory, forgotten, and so on. ๐ฆ
ErlNifPort
A port identifier. In contrast to port ID terms (instances of ERL_NIF_TERM), ErlNifPorts are self-contained and not bound to any environment. ErlNifPort is an opaque type. It can be copied, moved in memory, forgotten, and so on.
ErlNifResourceType
Each instance of ErlNifResourceType represents a class of memory-managed resource objects that can be garbage collected. Each resource type has a unique name and a destructor function that is called when objects of its type are released.
ErlNifResourceTypeInit
typedef struct {
ErlNifResourceDtor* dtor; // #1 Destructor
ErlNifResourceStop* stop; // #2 Select stop
ErlNifResourceDown* down; // #3 Monitor down
int members;
ErlNifResourceDynCall* dyncall; // #4 Dynamic call
} ErlNifResourceTypeInit;
Initialization structure read by enif_open_resource_type_x and enif_init_resource_type.
ErlNifResourceDtor
typedef void ErlNifResourceDtor(ErlNifEnv* caller_env, void* obj);
The obj argument is a pointer to the resource. The only allowed use for the resource in the destructor is to access its user data one final time. The destructor is guaranteed to be the last callback before the resource is deallocated. ๐
ErlNifResourceDownโ the function prototype of a resource down function, called on behalf ofenif_monitor_process.
typedef void ErlNifResourceDown(ErlNifEnv* caller_env, void* obj, ErlNifPid* pid, ErlNifMonitor* mon);
obj is the resource, pid is the identity of the monitored process that is exiting, and mon is the identity of the monitor. bestie that's the whole down-low, literally ๐ซถ
ErlNifResourceStopโ the function prototype of a resource stop function, called on behalf ofenif_select.
typedef void ErlNifResourceStop(ErlNifEnv* caller_env, void* obj, ErlNifEvent event, int is_direct_call);
obj is the resource, event is OS event, is_direct_call is true if the call is made directly from enif_select or false if it is a scheduled call (potentially from another thread). no cap โจ
ErlNifResourceDynCallโ the function prototype of a dynamic resource call function, called byenif_dynamic_resource_call.
typedef void ErlNifResourceDynCall(ErlNifEnv* caller_env, void* obj, void* call_data);
Argument obj is the resource object and call_data is the last argument to enif_dynamic_resource_call passed through. ๐
ErlNifCharEncodingโ the character encoding used in strings and atoms.
typedef enum {
ERL_NIF_LATIN1,
ERL_NIF_UTF8,
}ErlNifCharEncoding;
The only supported encodings are ERL_NIF_LATIN1 for ISO Latin-1 (8-bit ASCII) and ERL_NIF_UTF8 for UTF-8. two options, both iconic, pick your fave ๐
ErlNifSysInfo
Used by enif_system_info to return information about the runtime system. Contains the same content as ErlDrvSysInfo.
ErlNifSInt64
A native signed 64-bit integer type.
ErlNifUInt64
A native unsigned 64-bit integer type.
ErlNifTime
A signed 64-bit integer type for representation of time. โฐ
ErlNifTimeUnit
An enumeration of time units supported by the NIF API:
ERL_NIF_SECโ secondsERL_NIF_MSECโ millisecondsERL_NIF_USECโ microsecondsERL_NIF_NSECโ nanoseconds
s to ms to ยตs to ns, the whole timeline got a glow-up โจ
ErlNifUniqueInteger
An enumeration of the properties that can be requested from enif_make_unique_integer. For default properties, use value 0.
ERL_NIF_UNIQUE_POSITIVEโ return only positive integers.ERL_NIF_UNIQUE_MONOTONICโ return only strictly monotonically increasing integer corresponding to creation time.
ErlNifHash
An enumeration of the supported hash types that can be generated using enif_hash.
ERL_NIF_INTERNAL_HASHโ non-portable hash function that only guarantees the same hash for the same term within one Erlang VM instance.
It takes 32-bit salt values and generates hashes within 0..2^32-1.
ERL_NIF_PHASH2โ portable hash function that gives the same hash for the same Erlang term regardless of machine architecture and ERTS version.
It ignores salt values and generates hashes within 0..2^27-1.
Slower than ERL_NIF_INTERNAL_HASH. It corresponds to erlang:phash2/1.
SysIOVec
A system I/O vector, as used by writev on Unix and WSASend on Win32. It is used in ErlNifIOVec and by enif_ioq_peek.
ErlNifIOVecโ an I/O vector containingiovcntSysIOVecs pointing to the data. It is used byenif_inspect_iovecandenif_ioq_enqv.
typedef struct {
int iovcnt;
size_t size;
SysIOVec* iov;
} ErlNifIOVec;
ErlNifIOQueueOpts
Options to configure a ErlNifIOQueue.
ERL_NIF_IOQ_NORMALโ create a normal I/O Queue
enif_alloc()
void * enif_alloc(
size_t size);
Allocates memory of size bytes.
Returns NULL if the allocation fails.
The returned pointer is suitably aligned for any built-in type that fit in the allocated memory. ๐
enif_alloc_binary()
int enif_alloc_binary(
size_t size,
ErlNifBinary* bin);
Allocates a new binary of size size bytes. Initializes the structure pointed to by bin to refer to the allocated binary. The binary must either be released by enif_release_binary or ownership transferred to an Erlang term with enif_make_binary. An allocated (and owned) ErlNifBinary can be kept between NIF calls. so don't just ghost it, you gotta release it or hand it off, fr fr ๐
If you do not need to reallocate or keep the data alive across NIF calls, consider using enif_make_new_binary instead as it will allocate small binaries on the process heap when possible.
Returns true on success, or false if allocation fails.
enif_alloc_env()
ErlNifEnv * enif_alloc_env();
Allocates a new process independent environment. The environment can be used to hold terms that are not bound to any process. Such terms can later be copied to a process environment with enif_make_copy or be sent to a process as a message with enif_send.
Returns pointer to the new environment.
Available since OTP R14B ๐
enif_alloc_resource()
void * enif_alloc_resource(
ErlNifResourceType* type,
unsigned size);
Allocates a memory-managed resource object of type type and size size bytes.
Available since OTP R13B04 ๐
enif_binary_to_term()
size_t enif_binary_to_term(
ErlNifEnv *env,
const unsigned char* data,
size_t size,
ERL_NIF_TERM *term,
unsigned int opts);
Creates a term that is the result of decoding the binary data at data, which must be encoded according to the Erlang external term format. No more than size bytes are read from data. Argument opts corresponds to the second argument to erlang:binary_to_term/2 and must be either 0 or ERL_NIF_BIN2TERM_SAFE.
On success, stores the resulting term at *term and returns the number of bytes read. Returns 0 if decoding fails or if opts is invalid.
See also ErlNifBinaryToTerm, erlang:binary_to_term/2, and enif_term_to_binary.
Available since OTP 19.0 ๐
enif_clear_env()
void enif_clear_env(ErlNifEnv* env);
Frees all terms in an environment and clears it for reuse. The environment must have been allocated with enif_alloc_env. no sneaking in someone else's env, bestie ๐
Available since OTP R14B ๐
enif_compare()
int enif_compare(
ERL_NIF_TERM lhs,
ERL_NIF_TERM rhs);
Returns an integer < 0 if lhs < rhs, 0 if lhs = rhs, and > 0 if lhs > rhs. Corresponds to the Erlang operators ==, /=, =<, <, >=, and > (but not =:= or =/=).
read that again โ it's the loose comparison club, not the strict one ๐ญ
Available since OTP R13B04 ๐
enif_compare_monitors()
int enif_compare_monitors(
const ErlNifMonitor *monitor1,
const ErlNifMonitor *monitor2);
Compares two ErlNifMonitors. Can also be used to imply some artificial order on monitors, for whatever reason. ๐
Returns 0 if monitor1 and monitor2 are equal, < 0 if monitor1 < monitor2, and > 0 if monitor1 > monitor2.
Available since OTP 20.0 ๐
enif_compare_pids()
int enif_compare_pids(
const ErlNifPid *pid1,
const ErlNifPid *pid2);
Compares two ErlNifPids according to term order.
Returns 0 if pid1 and pid2 are equal, < 0 if pid1 < pid2, and > 0 if pid1 > pid2.
Available since OTP 22.0 ๐
enif_cond_broadcast()
void enif_cond_broadcast(
ErlNifCond *cnd);
Same as erl_drv_cond_broadcast.
Available since OTP R13B04 ๐
enif_cond_create()
ErlNifCond * enif_cond_create(
char *name);
Same as erl_drv_cond_create.
Available since OTP R13B04 ๐
enif_cond_destroy()
void enif_cond_destroy(
ErlNifCond *cnd);
Same as erl_drv_cond_destroy.
Available since OTP R13B04 ๐
enif_cond_name()
char* enif_cond_name(
ErlNifCond* cnd);
Same as erl_drv_cond_name.
Available since OTP 21.0 ๐
enif_cond_signal()
void enif_cond_signal(
ErlNifCond *cnd);
Same as erl_drv_cond_signal.
Available since OTP R13B04 ๐
enif_cond_wait()
void enif_cond_wait(
ErlNifCond *cnd,
ErlNifMutex *mtx);
Same as erl_drv_cond_wait.
Available since OTP R13B04 ๐
enif_consume_timeslice()
int enif_consume_timeslice(
ErlNifEnv *env,
int percent);
Gives the runtime system a hint about how much CPU time the current NIF call has consumed since the last hint, or since the start of the NIF if no previous hint has been specified. The time is specified as a percent of the timeslice that a process is allowed to execute Erlang code until it can be suspended to give time for other runnable processes. The scheduling timeslice is not an exact entity, but can usually be approximated to about 1 millisecond.
Notice that it is up to the runtime system to determine if and how to use this information. Implementations on some platforms can use other means to determine consumed CPU time. Lengthy NIFs should regardless of this frequently call enif_consume_timeslice to determine if it is allowed to continue execution. ๐
Argument percent must be an integer between 1 and 100. This function must only be called from a NIF-calling thread, and argument env must be the environment of the calling process.
Returns 1 if the timeslice is exhausted, otherwise 0. If 1 is returned, the NIF is to return as soon as possible in order for the process to yield.
This function is provided to better support co-operative scheduling, improve system responsiveness, and make it easier to prevent misbehaviors of the VM because of a NIF monopolizing a scheduler thread. It can be used to divide length work into a number of repeated NIF calls without the need to create threads.
See also the warning text at the beginning of this manual page. โ ๏ธ
Available since OTP R16B ๐
enif_convert_time_unit()
ErlNifTime enif_convert_time_unit(
ErlNifTime val,
ErlNifTimeUnit from,
ErlNifTimeUnit to);
Converts the val value of time unit from to the corresponding value of time unit to. The result is rounded using the floor function. ๐งฎ
valโ value to convert time unit for.fromโ time unit ofval.toโ time unit of returned value.
Returns ERL_NIF_TIME_ERROR if called with an invalid time unit argument.
See also ErlNifTime and ErlNifTimeUnit.
Available since OTP 18.3 ๐
enif_cpu_time() โฐ
ERL_NIF_TERM enif_cpu_time(
ErlNifEnv *env);
Hands you back the CPU time, formatted exactly like erlang:timestamp() does. What even is CPU time here? It's how long the current logical CPU has been busy executing since... some random point way back in the past, bestie, nobody knows when. If your OS just doesn't support grabbing this number, enif_cpu_time goes and calls enif_make_badarg. Rude, but okay. ๐
Available since OTP 19.0
enif_demonitor_process() ๐
int enif_demonitor_process(
ErlNifEnv* caller_env,
void* obj,
const ErlNifMonitor* mon);
Cancels a monitor you set up earlier with enif_monitor_process. The obj argument is a pointer to the resource that's holding the monitor, and *mon is what identifies which monitor we're talking about.
Now, caller_env is the environment of the calling thread โ that's a process bound environment or a callback environment. Pass NULL there if you're calling from a custom thread that ERTS did not spawn. ๐
So what do you get back?
0โ slay, the monitor was found and removed successfully โจ- A non-zero value โ the monitor could not be identified. Which means it was either:
- never created for this resource
- already cancelled
- already triggered
- just about to be triggered by a concurrent thread ๐ญ
This function is thread-safe.
Available since OTP 20.0
enif_dynamic_resource_call() ๐
int enif_dynamic_resource_call(
ErlNifEnv* caller_env,
ERL_NIF_TERM rt_module,
ERL_NIF_TERM rt_name,
ERL_NIF_TERM resource,
void* call_data);
This one lets you call code of a resource type that was implemented by a whole other NIF module. The atoms rt_module and rt_name together identify which resource type you're calling into, and resource points at a resource object of that type.
What happens next is the dyncall callback of that identified resource type gets called, receiving a pointer to the resource object's obj plus whatever call_data you passed through. Speaking of call_data โ it's usually a pointer to a struct, because you're typically using it both to shove arguments into the dyncall function and to bring results back out to the caller. Two-way street, love that for us. ๐ซถ
Return values:
0if thedyncallcallback function was called- non-zero if no call was made at all โ which happens when
rt_moduleandrt_namedidn't identify a resource type with adyncallcallback, or whenresourcewasn't a resource object of that type
Available since OTP 24.0
enif_equal_tids() ๐งต
int enif_equal_tids(
ErlNifTid tid1,
ErlNifTid tid2);
Same as erl_drv_equal_tids. That's it, that's the whole vibe.
Available since OTP R13B04
enif_fprintf() ๐จ๏ธ
int enif_fprintf(
FILE *stream,
const char *format,
...);
Basically fprintf, except this format string also takes "%T", which formats Erlang terms of type ERL_NIF_TERM. iconic.
Heads up though: this function is primarily intended for debugging purpose. And it is not recommended to print very large terms with%T. Also, the function may changeerrno, even if successful โ so don't come crying to me when your errno is doing its own thing. ๐
Available since OTP 21.0
enif_free() ๐๏ธ
void enif_free(
void* ptr);
Frees memory that was allocated by enif_alloc. Cleanup queen behavior.
enif_free_env() ๐งน
void enif_free_env(
ErlNifEnv* env);
Frees an environment that was allocated with enif_alloc_env. And yes, all terms created in that environment get freed as well โ they go down together, no survivors. ๐ซง
Available since OTP R14B
enif_free_iovec() ๐
void enif_free_iovec(
ErlNifIOVec* iov);
Frees an io vector that came back from enif_inspect_iovec. You only need this if you passed a NULL environment to enif_inspect_iovec โ otherwise don't bother, bestie.
ErlNifIOVec *iovec = NULL;
size_t max_elements = 128;
ERL_NIF_TERM tail;
if (!enif_inspect_iovec(NULL, max_elements, term, &tail, &iovec))
return 0;
// Do things with the iovec
/* Free the iovector, possibly in another thread or nif function call */
enif_free_iovec(iovec);
Available since OTP 20.1
enif_get_atom() ๐ค
int enif_get_atom(
ErlNifEnv *env,
ERL_NIF_TERM term,
char *buf,
unsigned size,
ErlNifCharEncoding encoding);
Writes a NUL-terminated string into the buffer that buf points to โ that buffer is size bytes big โ and that string is the string representation of the atom term, using encoding.
Returns the number of bytes written (including the terminating NUL byte), or 0 if term is not an atom with a maximum length of size-1 bytes in that encoding.
Available since OTP R13B04
enif_get_atom_length() ๐
int enif_get_atom_length(
ErlNifEnv *env,
ERL_NIF_TERM term,
unsigned *len,
ErlNifCharEncoding encoding);
Sets *len to the length of the atom term in encoding โ and to be clear, that's the number of bytes excluding the terminating NUL byte.
Returns true on success. Returns false if term is not an atom, or if the atom just cannot be encoded using encoding.
Available since OTP R14B
enif_get_double() ๐
int enif_get_double(
ErlNifEnv* env,
ERL_NIF_TERM term,
double* dp);
Sets *dp to the floating-point value of term.
Returns true on success, or false if term is not a float.
Available since OTP R13B04
enif_get_int() ๐ข
int enif_get_int(
ErlNifEnv* env,
ERL_NIF_TERM term,
int* ip);
Sets *ip to the integer value of term.
Returns true on success, or false if term is not an integer or is outside the bounds of type int.
enif_get_int64() ๐
int enif_get_int64(
ErlNifEnv* env,
ERL_NIF_TERM term,
ErlNifSInt64* ip);
Sets *ip to the integer value of term.
Returns true on success, or false if term is not an integer or is outside the bounds of a signed 64-bit integer.
Available since OTP R14B
enif_get_local_pid() ๐ช
int enif_get_local_pid(
ErlNifEnv* env,
ERL_NIF_TERM term,
ErlNifPid* pid);
If term is the pid of a node local process, this function initializes the pid variable *pid from it and returns true. Otherwise it returns false.
And nope โ no check is done to see if the process is alive. It could be fully gone and this function would not care even a little bit. ๐
NOTE:enif_get_local_pidwill returnfalseif argumenttermis the atomundefined.
Available since OTP R14B
enif_get_local_port() โ
int enif_get_local_port(
ErlNifEnv* env,
ERL_NIF_TERM term,
ErlNifPort* port_id);
If term identifies a node local port, this function initializes the port variable *port_id from it and returns true. Otherwise false.
Same deal as the pid one: no check is done to see if the port is alive. We're just reading the vibe check, not the pulse. ๐
Available since OTP 19.0
enif_get_list_cell() ๐งฉ
int enif_get_list_cell(
ErlNifEnv* env,
ERL_NIF_TERM list,
ERL_NIF_TERM* head,
ERL_NIF_TERM* tail);
Sets *head and *tail from the list list.
Returns true on success, or false if it's not a list or the list is empty.
enif_get_list_length() ๐
int enif_get_list_length(
ErlNifEnv* env,
ERL_NIF_TERM term,
unsigned* len);
Sets *len to the length of list term.
Returns true on success, or false if term is not a proper list.
Available since OTP R14B
enif_get_long() ๐ธ
int enif_get_long(
ErlNifEnv* env,
ERL_NIF_TERM term,
long int* ip);
Sets *ip to the long integer value of term.
Returns true on success, or false if term is not an integer or is outside the bounds of type long int.
Available since OTP R13B04
enif_get_map_size() ๐บ๏ธ
int enif_get_map_size(
ErlNifEnv* env,
ERL_NIF_TERM term,
size_t *size);
Sets *size to the number of key-value pairs in the map term.
Returns true on success, or false if term is not a map.
Available since OTP 18.0
enif_get_map_value() ๐
int enif_get_map_value(
ErlNifEnv* env,
ERL_NIF_TERM map,
ERL_NIF_TERM key,
ERL_NIF_TERM* value);
Sets *value to the value that's associated with key in the map map.
Returns true on success, or false if map is not a map, or if map doesn't contain key.
Available since OTP 18.0
enif_get_resource() ๐
int enif_get_resource(
ErlNifEnv* env,
ERL_NIF_TERM term,
ErlNifResourceType* type,
void** objp);
Sets *objp to point at the resource object that term refers to.
Returns true on success, or false if term is not a handle to a resource object of type type.
Important little detail: enif_get_resource does not add a reference to the resource object. However, the pointer you receive in *objp is guaranteed to be valid at least as long as the resource handle term is valid. So don't get cute and let that term die on you. ๐ญ
Available since OTP R13B04
enif_get_string() ๐ชข
int enif_get_string(
ErlNifEnv* env,
ERL_NIF_TERM list,
char* buf,
unsigned size,
ErlNifCharEncoding encoding);
Writes a NUL-terminated string into the buffer that buf points to โ size size โ made up of the characters in the string list. Those characters get written using encoding.
Returns one of the following:
- The number of bytes written (including the terminating NUL byte)
-sizeif the string was truncated because of buffer space0iflistis not a string that can be encoded withencoding, or ifsizewas0
And a lil reassurance: the written string is always NUL-terminated โ unless buffer size is 0, obviously. ๐
Available since OTP R13B04
enif_get_string_length() โจ
int enif_get_string_length(
ErlNifEnv *env,
ERL_NIF_TERM list,
unsigned *len,
ErlNifCharEncoding encoding);
Sets *len to the length of the string list in encoding โ the number of bytes excluding the terminating NUL byte, same rules as always.
Returns true on success, or false if list is not a string that can be encoded with encoding.
Available since OTP 26.0
enif_get_tuple() ๐
int enif_get_tuple(
ErlNifEnv* env,
ERL_NIF_TERM term,
int* arity,
const ERL_NIF_TERM** array);
If term is a tuple, this function sets *array to point at an array holding the tuple's elements, and sets *arity to the number of elements. Little details that matter: the array is read-only, and (*array)[N-1] is the Nth element of the tuple. Also, *array is undefined if the arity of the tuple is zero โ so don't go dereferencing that, bestie. ๐
Returns true on success, or false if term is not a tuple.
Available since OTP R13B04
enif_get_uint()
int enif_get_uint(
ErlNifEnv* env,
ERL_NIF_TERM term,
unsigned int* ip);
Sets *ip to the unsigned integer value sitting inside term. ๐
Returns true if it ate, or false if term is not an unsigned integer or it's too big/small to fit in a plain unsigned int. So likeโฆ out of bounds, no entry, bestie. ๐ญ
Available since OTP R13B04
enif_get_uint64()
int enif_get_uint64(
ErlNifEnv* env,
ERL_NIF_TERM term,
ErlNifUInt64* ip);
Sets *ip to the unsigned integer value of term. Same energy, bigger container. โจ
Returns true on success, or false if term is not an unsigned integer or falls outside the bounds of an unsigned 64-bit integer.
Available since OTP R14B
enif_get_ulong()
int enif_get_ulong(
ErlNifEnv* env,
ERL_NIF_TERM term,
unsigned long* ip);
Sets *ip to the unsigned long integer value of term. ๐
Returns true on success, or false if term is not an unsigned integer or is outside the bounds of type unsigned long.
enif_getenv()
int enif_getenv(
const char* key,
char* value,
size_t *value_size);
Literally the same as erl_drv_getenv. That's it, that's the whole thing. ๐ซถ
Available since OTP 18.2
enif_has_pending_exception()
int enif_has_pending_exception(
ErlNifEnv* env,
ERL_NIF_TERM* reason);
Returns true if there's a pending exception attached to the environment env. ๐จ
If reason is a NULL pointer, ignore it, whatever, it's not important. Otherwise โ if a pending exception associated with env actually exists โ it sets *reason to the value of that exception term.
For example: if enif_make_badarg gets called and sets a pending badarg exception, then a later call to enif_has_pending_exception(env, &reason) sets *reason to the atom badarg, and then returns true. Chef's kiss. ๐
See also enif_make_badarg and enif_raise_exception.
Available since OTP 18.0
enif_hash()
ErlNifUInt64 enif_hash(
ErlNifHash type,
ERL_NIF_TERM term,
ErlNifUInt64 salt);
Hashes term according to the ErlNifHash type you picked. ๐ง
The ranges of the taken salt (if any) and the returned value both depend on the hash type. So like, don't assume, okay? iykyk.
Available since OTP 20.0
enif_inspect_binary()
int enif_inspect_binary(
ErlNifEnv* env,
ERL_NIF_TERM bin_term,
ErlNifBinary* bin);
Initializes the structure that bin points to with info about the binary term bin_term. ๐
The data that bin points to is transient โ it does not need to be released, unless you later reallocated it with enif_realloc_binary.
Returns true on success, or false if bin_term is not a binary.
enif_inspect_iolist_as_binary()
int enif_inspect_iolist_as_binary(
ErlNifEnv* env,
ERL_NIF_TERM term,
ErlNifBinary* bin);
Initializes the structure pointed to by bin with a continuous buffer holding the same byte content as iolist. ๐
Same deal as inspect_binary: the data pointed to by bin is transient and doesn't need releasing unless it was later reallocated with enif_realloc_binary.
Returns true on success, or false if iolist is not an iolist.
Available since OTP R13B04
enif_inspect_iovec()
int enif_inspect_iovec(
ErlNifEnv* env,
size_t max_elements,
ERL_NIF_TERM iovec_term,
ERL_NIF_TERM* tail,
ErlNifIOVec** iovec);
Fills iovec with the list of binaries handed to you in iovec_term. โจ The number of elements handled in the call is capped at max_elements, and tail gets set to the remainder of the list.
Heads up bestie: the output may be longer than max_elements on some platforms. No cap (literally). ๐
To build a list of binaries out of an arbitrary iolist, use erlang:iolist_to_iovec/1.
When you call this function, iovec should contain a pointer to NULL, or a ErlNifIOVec structure that should be used if possible. Like so:
/* Don't use a pre-allocated structure */
ErlNifIOVec *iovec = NULL;
enif_inspect_iovec(env, max_elements, term, &tail, &iovec);
/* Use a stack-allocated vector as an optimization for vectors with few elements */
ErlNifIOVec vec, *iovec = &vec;
enif_inspect_iovec(env, max_elements, term, &tail, &iovec);
The contents of the iovec stay valid until the called nif function returns. If you need the iovec to still be valid after the nif call returns, you can call this function with a NULL environment. If no environment is given, the iovec owns the data in the vector and it has to be explicitly freed using enif_free_iovec. ๐งน
Returns true on success, or false if iovec_term is not an iovec.
Available since OTP 20.1
enif_ioq_create()
ErlNifIOQueue * enif_ioq_create(
ErlNifIOQueueOpts opts);
Creates a brand new I/O Queue you can use to store data. ๐ opts has to be set to ERL_NIF_IOQ_NORMAL.
Available since OTP 20.1
enif_ioq_destroy()
void enif_ioq_destroy(
ErlNifIOQueue *q);
Destroys the I/O queue and frees all of it's contents. Gone. Poof. ๐ฆ
Available since OTP 20.1
enif_ioq_deq()
int enif_ioq_deq(
ErlNifIOQueue *q,
size_t count,
size_t *size);
Dequeues count bytes from the I/O queue. If size is not NULL, the new size of the queue gets placed there. ๐
Returns true on success, or false if the I/O does not contain count bytes. On failure the queue is left un-altered โ untouched, icon behavior honestly.
Available since OTP 20.1
enif_ioq_enq_binary()
int enif_ioq_enq_binary(
ErlNifIOQueue *q,
ErlNifBinary *bin,
size_t skip);
Enqueues the bin into q, skipping the first skip bytes. โจ
Returns true on success, or false if skip is greater than the size of bin.
Any ownership of the binary data is transferred to the queue, and bin is to be considered read-only for the rest of the NIF call, and then as released. So hands off, bestie. ๐
Available since OTP 20.1
enif_ioq_enqv()
int enif_ioq_enqv(
ErlNifIOQueue *q,
ErlNifIOVec *iovec,
size_t skip);
Enqueues the iovec into q, skipping the first skip bytes. ๐
Returns true on success, or false if skip is greater than the size of iovec.
Available since OTP 20.1
enif_ioq_peek()
SysIOVec * enif_ioq_peek(
ErlNifIOQueue *q,
int *iovlen);
Gets the I/O queue as a pointer to an array of SysIOVecs. It also returns the number of elements in iovlen. ๐
Nothing is removed from the queue by this function โ that's a job for enif_ioq_deq. Peek responsibly.
The returned array is suitable to use with the Unix system call writev. ๐ฅ
Available since OTP 20.1
enif_ioq_peek_head()
int enif_ioq_peek_head(
ErlNifEnv *env,
ErlNifIOQueue *q,
size_t *size,
ERL_NIF_TERM *bin_term);
Gets the head of the IO Queue as a binary term. ๐
If size is not NULL, the size of the head is placed there.
Nothing is removed from the queue by this function, that must be done with enif_ioq_deq. Again. Because we respect the queue's boundaries.
Returns true on success, or false if the queue is empty.
Available since OTP 21.0
enif_ioq_size()
size_t enif_ioq_size(
ErlNifIOQueue *q);
Gets the size of q. That's it. That's the function. ๐
Available since OTP 20.1
enif_is_atom()
int enif_is_atom(
ErlNifEnv* env,
ERL_NIF_TERM term);
Returns true if term is an atom. โญ
Available since OTP R13B04
enif_is_binary()
int enif_is_binary(
ErlNifEnv* env,
ERL_NIF_TERM term);
Returns true if term is a binary. ๐ฆ
enif_is_current_process_alive()
int enif_is_current_process_alive(
ErlNifEnv* env);
Returns true if the currently executing process is currently alive, otherwise false. ๐
This function can only be used from a NIF-calling thread, and with an environment corresponding to currently executing processes. Respect the rules or it's giving undefined behavior.
Available since OTP 19.0
enif_is_empty_list()
int enif_is_empty_list(
ErlNifEnv* env,
ERL_NIF_TERM term);
Returns true if term is an empty list. [] girlies rise. ๐
Available since OTP R13B04
enif_is_exception()
int enif_is_exception(
ErlNifEnv* env,
ERL_NIF_TERM term);
Returns true if term is an exception. ๐จ
Available since OTP R14B03
enif_is_fun()
int enif_is_fun(
ErlNifEnv* env,
ERL_NIF_TERM term);
Returns true if term is a fun. โจ
Available since OTP R13B04
enif_is_identical()
int enif_is_identical(
ERL_NIF_TERM lhs,
ERL_NIF_TERM rhs);
Returns true if the two terms are identical. ๐ This corresponds to the Erlang operators =:= and =/=.
Available since OTP R13B04
enif_is_list()
int enif_is_list(
ErlNifEnv* env,
ERL_NIF_TERM term);
Returns true if term is a list. ๐ธ
Available since OTP R14B
enif_is_map()
int enif_is_map(
ErlNifEnv* env,
ERL_NIF_TERM term);
Returns true if term is a map, otherwise false. ๐บ๏ธ
Available since OTP 18.0
enif_is_number()
int enif_is_number(
ErlNifEnv* env,
ERL_NIF_TERM term);
Returns true if term is a number. ๐ข
Available since OTP R15B
enif_is_pid()
int enif_is_pid(
ErlNifEnv* env,
ERL_NIF_TERM term);
Returns true if term is a pid. ๐
Available since OTP R13B04
enif_is_pid_undefined()
int enif_is_pid_undefined(
const ErlNifPid* pid);
Returns true if pid has been set as undefined by enif_set_pid_undefined. ๐ซฅ
Available since OTP 22.0
enif_is_port()
int enif_is_port(
ErlNifEnv* env,
ERL_NIF_TERM term);
Returns true if term is a port. ๐ช
Available since OTP R13B04
enif_is_port_alive()
int enif_is_port_alive(
ErlNifEnv* env,
ErlNifPort *port_id);
Returns true if port_id is alive. ๐
This function is thread-safe.
Available since OTP 19.0
enif_is_process_alive()
int enif_is_process_alive(
ErlNifEnv* env,
ErlNifPid *pid);
Returns true if pid is alive. ๐
This function is thread-safe.
Available since OTP 19.0
enif_is_ref()
int enif_is_ref(
ErlNifEnv* env,
ERL_NIF_TERM term);
Returns true if term is a reference. ๐ช
Available since OTP R13B04
๐ enif_is_tuple()
int enif_is_tuple(
ErlNifEnv* env,
ERL_NIF_TERM term);
Returns true if term is a tuple. That's the whole vibe check bestie, it's a yes-or-no situation. ๐
โจ Available since OTP R14B
๐
enif_keep_resource()
int enif_keep_resource(
void* obj);
Adds a reference to the resource object obj that you got from enif_alloc_resource. And listen, this is a balance your books situation: every single call to enif_keep_resource for an object must be balanced by a call to enif_release_resource before the object gets destructed. No skipping, no vibes-based memory management, fr fr. ๐ญ
โจ Available since OTP R14B
๐ธ enif_make_atom()
ERL_NIF_TERM enif_make_atom(
ErlNifEnv *env,
const char *name);
Creates an atom term from the NUL-terminated C-string name, with ISO Latin-1 encoding. And if the length of name exceeds the maximum length allowed for an atom (255 characters), enif_make_atom invokes enif_make_badarg. So likeโฆ behave. ๐
๐ฆ enif_make_atom_len()
ERL_NIF_TERM enif_make_atom_len(
ErlNifEnv *env,
const char *name,
size_t len);
Creates an atom term from the string name with length len and ISO Latin-1 encoding. NUL bytes are treated as any other characters โ no special treatment for the little guys, they're just part of the crew. ๐
If len exceeds the maximum length allowed for an atom (255 characters), enif_make_atom invokes enif_make_badarg .
โจ Available since OTP R14B
๐ enif_make_badarg()
ERL_NIF_TERM enif_make_badarg(
ErlNifEnv* env);
Makes a badarg exception to be returned from a NIF, and associates it with environment env. Once a NIF or any function it calls invokes enif_make_badarg, the runtime ensures that a badarg exception is raised when the NIF returns โ even if the NIF attempts to return a non-exception term instead. Like, you can try to sneak a normal term past her and she WILL catch it. ๐ซถ
The return value from enif_make_badarg can be used only as the return value from the NIF that invoked it (directly or indirectly) or be passed to enif_is_exception, but not to any other NIF API function. Read that again bestie, it's strict. ๐ฅ
See also enif_has_pending_exception and enif_raise_exception.
NOTE: Before ERTS 7.0 (Erlang/OTP 18), the return value fromenif_make_badarghad to be returned from the NIF. This requirement is now lifted as the return value from the NIF is ignored ifenif_make_badarghas been invoked.
๐ enif_make_binary()
ERL_NIF_TERM enif_make_binary(
ErlNifEnv* env,
ErlNifBinary* bin);
Makes a binary term from bin. Any ownership of the binary data is transferred to the created term, and bin is to be considered read-only for the rest of the NIF call and then as released. So like, she took custody, hand over the keys and stop touching it. ๐
โจ enif_make_copy()
ERL_NIF_TERM enif_make_copy(
ErlNifEnv* dst_env,
ERL_NIF_TERM src_term);
Makes a copy of term src_term. The copy is created in environment dst_env. The source term can be located in any environment โ she doesn't care where it came from, she'll copy it anyway. main character energy. ๐
โจ Available since OTP R14B
๐ enif_make_double()
ERL_NIF_TERM enif_make_double(
ErlNifEnv* env,
double d);
Creates a floating-point term from a double. If argument double is not finite or is NaN, enif_make_double invokes enif_make_badarg. Infinity and NaN are NOT invited to this party, no cap. ๐
โจ Available since OTP R13B04
๐ซ enif_make_existing_atom()
int enif_make_existing_atom(
ErlNifEnv *env,
const char *name,
ERL_NIF_TERM *atom,
ErlNifCharEncoding encoding);
Tries to create the term of an already existing atom from the NUL-terminated C-string name with encoding.
If the atom already exists, this function stores the term in *atom and returns true, otherwise returns false. It also returns false if the string name exceeds the maximum length allowed for an atom (255 characters) or if name is not correctly encoded. So many ways to get a false here, it's giving "audition gone wrong". ๐ญ
โจ Available since OTP R13B04
๐ง enif_make_existing_atom_len()
int enif_make_existing_atom_len(
ErlNifEnv *env,
const char *name,
size_t len,
ERL_NIF_TERM *atom,
ErlNifCharEncoding encoding);
Tries to create the term of an already existing atom from the string name with length len bytes and encoding. NUL bytes are treated as any other characters.
If the atom already exists, this function stores the term in *atom and returns true, otherwise returns false. It also returns false if the string name exceeds the maximum length allowed for an atom (255 characters) or if name is not correctly encoded.
โจ Available since OTP R14B
๐ enif_make_int()
ERL_NIF_TERM enif_make_int(
ErlNifEnv* env,
int i);
Creates an integer term. Short, sweet, iconic. ๐
๐ฅ enif_make_int64()
ERL_NIF_TERM enif_make_int64(
ErlNifEnv* env,
ErlNifSInt64 i);
Creates an integer term from a signed 64-bit integer. Big number energy. ๐ช
โจ Available since OTP R14B
๐ธ enif_make_list()
ERL_NIF_TERM enif_make_list(
ErlNifEnv* env,
unsigned cnt,
...);
Creates 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.
Returns an empty list if cnt is 0.
๐ enif_make_list1()
๐ enif_make_list2()
๐ enif_make_list3()
๐ enif_make_list4()
๐ enif_make_list5()
๐ enif_make_list6()
๐ enif_make_list7()
๐ enif_make_list8()
๐ enif_make_list9()
ERL_NIF_TERM enif_make_list1(
ErlNifEnv* env,
ERL_NIF_TERM e1);
ERL_NIF_TERM enif_make_list2(
ErlNifEnv* env,
ERL_NIF_TERM e1, ERL_NIF_TERM e2);
ERL_NIF_TERM enif_make_list3(
ErlNifEnv* env,
ERL_NIF_TERM e1, ERL_NIF_TERM e2, ERL_NIF_TERM e3);
ERL_NIF_TERM enif_make_list4(
ErlNifEnv* env,
ERL_NIF_TERM e1, ..., ERL_NIF_TERM e4);
ERL_NIF_TERM enif_make_list5(
ErlNifEnv* env,
ERL_NIF_TERM e1, ..., ERL_NIF_TERM e5);
ERL_NIF_TERM enif_make_list6(
ErlNifEnv* env,
ERL_NIF_TERM e1, ..., ERL_NIF_TERM e6);
ERL_NIF_TERM enif_make_list7(
ErlNifEnv* env,
ERL_NIF_TERM e1, ..., ERL_NIF_TERM e7);
ERL_NIF_TERM enif_make_list8(
ErlNifEnv* env,
ERL_NIF_TERM e1, ..., ERL_NIF_TERM e8);
ERL_NIF_TERM enif_make_list9(
ErlNifEnv* env,
ERL_NIF_TERM e1, ..., ERL_NIF_TERM e9);
Creates an ordinary list term with length indicated by the function name. And okay bestie, real talk: prefer these functions (macros) over the variadic enif_make_list to get a compile-time error if the number of arguments does not match. Catching your own mistakes at compile time is highkey the slayest thing you can do. ๐ซถ
โจ Available since OTP R13B04
๐ enif_make_list_cell()
ERL_NIF_TERM enif_make_list_cell(
ErlNifEnv* env,
ERL_NIF_TERM head,
ERL_NIF_TERM tail);
Creates a list cell [head | tail]. She's little but she's everything. ๐ฅน
โญ enif_make_list_from_array()
ERL_NIF_TERM enif_make_list_from_array(
ErlNifEnv* env,
const ERL_NIF_TERM arr[],
unsigned cnt);
Creates an ordinary list containing the elements of array arr of length cnt.
Returns an empty list if cnt is 0.
โจ Available since OTP R13B04
๐ฆ enif_make_long()
ERL_NIF_TERM enif_make_long(
ErlNifEnv* env,
long int i);
Creates an integer term from a long int. Yes queen, use the long one. ๐
โจ Available since OTP R13B04
๐ enif_make_map_put()
int enif_make_map_put(
ErlNifEnv* env,
ERL_NIF_TERM map_in,
ERL_NIF_TERM key,
ERL_NIF_TERM value,
ERL_NIF_TERM* map_out);
Makes a copy of map map_in and inserts key with value. If key already exists in map_in, the old associated value is replaced by value. Out with the old, in with the new, no drama. ๐
If successful, this function sets *map_out to the new map and returns true. Returns false if map_in is not a map.
The map_in term must belong to environment env.
โจ Available since OTP 18.0
โจ enif_make_map_remove()
int enif_make_map_remove(
ErlNifEnv* env,
ERL_NIF_TERM map_in,
ERL_NIF_TERM key,
ERL_NIF_TERM* map_out);
If map map_in contains key, this function makes a copy of map_in in *map_out, and removes key and the associated value. If map map_in does not contain key, *map_out is set to map_in. (No key, no copy, just vibes โ she hands you back the same map.) ๐
Returns true on success, or false if map_in is not a map.
The map_in term must belong to environment env.
โจ Available since OTP 18.0
๐ฅ enif_make_map_update()
int enif_make_map_update(
ErlNifEnv* env,
ERL_NIF_TERM map_in,
ERL_NIF_TERM key,
ERL_NIF_TERM new_value,
ERL_NIF_TERM* map_out);
Makes a copy of map map_in and replaces the old associated value for key with new_value. Glow-up applied. โจ
If successful, this function sets *map_out to the new map and returns true. Returns false if map_in is not a map or if it does not contain key. So like, if the key isn't there she's not going to manifest it for you, bestie. ๐ญ
The map_in term must belong to environment env.
โจ Available since OTP 18.0
๐ enif_make_map_from_arrays()
int enif_make_map_from_arrays(
ErlNifEnv* env,
ERL_NIF_TERM keys[],
ERL_NIF_TERM values[],
size_t cnt,
ERL_NIF_TERM *map_out);
Makes a map term from the given keys and values. Build-a-map workshop, come through. ๐ง
If successful, this function sets *map_out to the new map and returns true. Returns false there are any duplicate keys. And no, she will NOT silently pick one, duplicates are a whole red flag. ๐ฉ
All keys and values must belong to env.
โจ Available since OTP 21.0
๐ธ enif_make_monitor_term()
ERL_NIF_TERM enif_make_monitor_term(
ErlNifEnv* env,
const ErlNifMonitor* mon);
Creates a term identifying the given monitor received from enif_monitor_process .
This function is primarily intended for debugging purpose. Like she's a backstage pass, not a headline act. ๐๏ธ
โจ Available since OTP 22.0
๐ enif_make_new_atom()
int enif_make_new_atom(
ErlNifEnv *env,
const char *name,
ERL_NIF_TERM *atom,
ErlNifCharEncoding encoding);
Creates an atom term from the NUL-terminated C-string name with encoding.
If successful, true is returned and the atom term is stored in *atom.
Otherwise, false is returned if the length of name exceeds the maximum length allowed for an atom (255 characters) or if name is not correctly encoded.
โจ Available since OTP 26.0
๐ซถ enif_make_new_atom_len()
int enif_make_new_atom_len(
ErlNifEnv *env,
const char *name,
size_t len,
ERL_NIF_TERM *atom,
ErlNifCharEncoding encoding);
okay hold on one sec bestie, she's mid-sentence ๐ โจ
Okay so this one's the atom-maker with explicit length and encoding โ it builds a term from the string name using len bytes and the given encoding.
If it works, you get true back and the atom term lands in *atom.
If it doesn't work, you get false โ and that happens in two cases: the string is longer than the max an atom is allowed to be (255 characters), or the string isn't correctly encoded. ๐
Available since OTP 26.0
enif_make_new_binary() ๐
unsigned char * enif_make_new_binary(
ErlNifEnv* env,
size_t size,
ERL_NIF_TERM* termp);
Allocates a binary of size bytes and makes an owning term out of it. The binary data stays mutable until the calling NIF returns โ that's the whole point. It's the fast lane to a fresh binary without having to mess around with ErlNifBinary. ๐๏ธ
The tradeoffs, bestie, are real: the binary cannot be kept between NIF calls, and it cannot be reallocated.
Returns a pointer to the raw binary data and sets *termp to the binary term.
Available since OTP R14B
enif_make_new_map() ๐บ๏ธ
ERL_NIF_TERM enif_make_new_map(
ErlNifEnv* env);
Makes an empty map term. That's it, that's the function, she's simple and she serves. โจ
Available since OTP 18.0
enif_make_pid() ๐
ERL_NIF_TERM enif_make_pid(
ErlNifEnv* env,
const ErlNifPid* pid);
Makes a pid term, or the atom undefined, from *pid.
Available since OTP R14B
enif_make_ref() ๐
ERL_NIF_TERM enif_make_ref(
ErlNifEnv* env);
Creates a reference, exactly like erlang:make_ref/0.
Available since OTP R13B04
enif_make_resource() ๐ฆ
ERL_NIF_TERM enif_make_resource(
ErlNifEnv* env,
void* obj);
Creates an opaque handle to a memory-managed resource object you got from enif_alloc_resource. No ownership transfer happens โ the resource object still needs to be released by enif_release_resource. But listen: the call to enif_release_resource can happen immediately after you get the term from enif_make_resource, and in that case the resource object gets deallocated when the term is garbage collected. For the deets, go look at the example of creating and returning a resource object in the User's Guide.
NOTE: Since ERTS 9.0 (OTP-20.0), resource terms have a defined behavior when compared and serialized through term_to_binary or passed between nodes.
- Two resource terms will compare equal if and only if they would yield the same resource object pointer when passed to
enif_get_resource. - A resource term can be serialized with
term_to_binaryand later be fully recreated if the resource object is still alive whenbinary_to_termis called. A stale resource term will be returned frombinary_to_termif the resource object has been deallocated.enif_get_resourcewill returnfalsefor stale resource terms. The same principles of serialization apply when passing resource terms in messages to remote nodes and back again. A resource term will act stale on all nodes except the node where its resource object is still alive in memory. Before ERTS 9.0 (OTP-20.0), all resource terms did compare equal to each other and to empty binaries (<<>>). If serialized, they would be recreated as plain empty binaries.
Available since OTP R13B04
enif_make_resource_binary() ๐
ERL_NIF_TERM enif_make_resource_binary(
ErlNifEnv* env,
void* obj,
const void* data,
size_t size);
Creates a binary term that's memory-managed by a resource object obj obtained by enif_alloc_resource. The returned binary term consists of size bytes pointed to by data. That raw binary data must be kept readable and unchanged until the destructor of the resource is called. The binary data can live external to the resource object, in which case the destructor is the one responsible for releasing the data.
Several binary terms can be managed by the same resource object. The destructor is not called until the last binary is garbage collected โ which is genuinely so useful if you want to hand out different parts of a larger binary buffer. ๐ธ
Same as with enif_make_resource: no ownership transfer. The resource still needs to be released with enif_release_resource.
Available since OTP R14B
enif_make_reverse_list() ๐
int enif_make_reverse_list(
ErlNifEnv* env,
ERL_NIF_TERM list_in,
ERL_NIF_TERM *list_out);
Sets *list_out to the reverse list of the list list_in and returns true. Returns false if list_in isn't a list.
โ ๏ธ Only use this on short lists, because a copy of the list gets created, and that copy isn't released until after the NIF returns.
The list_in term must belong to environment env.
Available since OTP R15B
enif_make_string() ๐
ERL_NIF_TERM enif_make_string(
ErlNifEnv *env,
const char *string,
ErlNifCharEncoding encoding);
Creates a list containing the characters of the NUL-terminated string string with encoding.
enif_make_string_len() ๐
ERL_NIF_TERM enif_make_string_len(
ErlNifEnv *env,
const char *string,
size_t len,
ErlNifCharEncoding encoding);
Creates a list containing the characters of the string string with length len and encoding. NUL bytes are treated as any other characters โ no sneaky early stopping here. ๐
Available since OTP R14B
enif_make_sub_binary() โ๏ธ
ERL_NIF_TERM enif_make_sub_binary(
ErlNifEnv* env,
ERL_NIF_TERM bin_term,
size_t pos,
size_t size);
Makes a subbinary of binary bin_term, starting at zero-based position pos with a length of size bytes. bin_term must be a binary or bitstring, and pos+size must be less or equal to the number of whole bytes in bin_term.
Available since OTP R13B04
enif_make_tuple() ๐
ERL_NIF_TERM enif_make_tuple(
ErlNifEnv* env,
unsigned cnt,
...);
Creates a tuple term of arity cnt. Expects cnt number of arguments (after cnt) of type ERL_NIF_TERM as the elements of the tuple.
enif_make_tuple1() through enif_make_tuple9() ๐ฏ
ERL_NIF_TERM enif_make_tuple1(
ErlNifEnv* env,
ERL_NIF_TERM e1);
ERL_NIF_TERM enif_make_tuple2(
ErlNifEnv* env,
ERL_NIF_TERM e1, ERL_NIF_TERM e2);
ERL_NIF_TERM enif_make_tuple3(
ErlNifEnv* env,
ERL_NIF_TERM e1, ERL_NIF_TERM e2, ERL_NIF_TERM e3);
ERL_NIF_TERM enif_make_tuple4(
ErlNifEnv* env,
ERL_NIF_TERM e1, ..., ERL_NIF_TERM e4);
ERL_NIF_TERM enif_make_tuple5(
ErlNifEnv* env,
ERL_NIF_TERM e1, ..., ERL_NIF_TERM e5);
ERL_NIF_TERM enif_make_tuple6(
ErlNifEnv* env,
ERL_NIF_TERM e1, ..., ERL_NIF_TERM e6);
ERL_NIF_TERM enif_make_tuple7(
ErlNifEnv* env,
ERL_NIF_TERM e1, ..., ERL_NIF_TERM e7);
ERL_NIF_TERM enif_make_tuple8(
ErlNifEnv* env,
ERL_NIF_TERM e1, ..., ERL_NIF_TERM e8);
ERL_NIF_TERM enif_make_tuple9(
ErlNifEnv* env,
ERL_NIF_TERM e1, ..., ERL_NIF_TERM e9);
Creates a tuple term with the length indicated by the function name. Prefer these functions (macros) over the variadic enif_make_tuple, because you get a compile-time error if the number of arguments doesn't match. Catching it at compile time is the moment, fr fr. ๐โจ
Available since OTP R13B04
enif_make_tuple_from_array() ๐งบ
ERL_NIF_TERM enif_make_tuple_from_array(
ErlNifEnv* env,
const ERL_NIF_TERM arr[],
unsigned cnt);
Creates a tuple containing the elements of array arr of length cnt.
Available since OTP R13B04
enif_make_uint() ๐ข
ERL_NIF_TERM enif_make_uint(
ErlNifEnv* env,
unsigned int i);
Creates an integer term from an unsigned int.
Available since OTP R13B04
enif_make_uint64() ๐
ERL_NIF_TERM enif_make_uint64(
ErlNifEnv* env,
ErlNifUInt64 i);
Creates an integer term from an unsigned 64-bit integer.
Available since OTP R14B
enif_make_ulong() ๐
ERL_NIF_TERM enif_make_ulong(
ErlNifEnv* env,
unsigned long i);
Creates an integer term from an unsigned long int.
enif_make_unique_integer() ๐
ERL_NIF_TERM enif_make_unique_integer(
ErlNifEnv *env,
ErlNifUniqueInteger properties);
Returns a unique integer with the same properties as specified by erlang:unique_integer/1.
env is the environment to create the integer in.
ERL_NIF_UNIQUE_POSITIVE and ERL_NIF_UNIQUE_MONOTONIC can be passed as the second argument to change the properties of the integer returned. They can be combined by OR:ing the two values together.
See also ErlNifUniqueInteger.
Available since OTP 19.0
enif_map_iterator_create() ๐บ๏ธ๐ซ
int enif_map_iterator_create(
ErlNifEnv *env,
ERL_NIF_TERM map,
ErlNifMapIterator *iter,
ErlNifMapIteratorEntry entry);
Creates an iterator for the map map by initializing the structure pointed to by iter. Argument entry determines the start position of the iterator: ERL_NIF_MAP_ITERATOR_FIRST or ERL_NIF_MAP_ITERATOR_LAST.
Returns true on success, or false if map is not a map.
A map iterator is only useful during the lifetime of environment env that the map belongs to. The iterator must be destroyed by calling enif_map_iterator_destroy:
ERL_NIF_TERM key, value;
ErlNifMapIterator iter;
enif_map_iterator_create(env, my_map, &iter, ERL_NIF_MAP_ITERATOR_FIRST);
while (enif_map_iterator_get_pair(env, &iter, &key, &value)) {
do_something(key,value);
enif_map_iterator_next(env, &iter);
}
enif_map_iterator_destroy(env, &iter);
NOTE: The key-value pairs of a map have no defined iteration order. The only guarantee is that the iteration order of a single map instance is preserved during the lifetime of the environment that the map belongs to.
Available since OTP 18.0
enif_map_iterator_destroy() ๐งน
void enif_map_iterator_destroy(
ErlNifEnv *env,
ErlNifMapIterator *iter);
Destroys a map iterator created by enif_map_iterator_create. Clean up after yourself, bestie, the iterator is not gonna release itself. ๐ซถ
Available since OTP 18.0
enif_map_iterator_get_pair()
int enif_map_iterator_get_pair(
ErlNifEnv *env,
ErlNifMapIterator *iter,
ERL_NIF_TERM *key,
ERL_NIF_TERM *value);
Grabs the key and the value sitting at wherever the map iterator currently is ๐
Sets *key and *value and hands you back true when it works.
It says false when the iterator is parked at head (that's before the first entry) or at tail (that's beyond the last entry), because bestie there's literally nothing there to grab ๐
Available since OTP 18.0
enif_map_iterator_is_head()
int enif_map_iterator_is_head(
ErlNifEnv *env,
ErlNifMapIterator *iter);
Returns true if map iterator iter is chillin' before the first entry ๐
Available since OTP 18.0
enif_map_iterator_is_tail()
int enif_map_iterator_is_tail(
ErlNifEnv *env,
ErlNifMapIterator *iter);
Returns true if map iterator iter is way out past the last entry, like it wandered off the end of the party ๐ธ
Available since OTP 18.0
enif_map_iterator_next()
int enif_map_iterator_next(
ErlNifEnv *env,
ErlNifMapIterator *iter);
Increments the map iterator so it points at the next key-value entry โจ
Returns true if the iterator is now sitting on a valid key-value entry, or false if it's chillin' at the tail (beyond the last entry). No cap ๐ซถ
Available since OTP 18.0
enif_map_iterator_prev()
int enif_map_iterator_prev(
ErlNifEnv *env,
ErlNifMapIterator *iter);
Decrements the map iterator so it points at the previous key-value entry, going backwards like a lil rewind โช
Returns true if the iterator is now positioned at a valid key-value entry, or false if it's sitting at the head (before the first entry). fr fr ๐
Available since OTP 18.0
enif_monitor_process()
int enif_monitor_process(
ErlNifEnv* caller_env,
void* obj,
const ErlNifPid* target_pid,
ErlNifMonitor* mon);
Starts monitoring a process from a resource. The way this works is: once a process is monitored, a process exit triggers a call to the down callback that's associated with the resource type ๐
obj is the pointer to the resource that's gonna hold the monitor, and *target_pid identifies the local process that's getting monitored.
If mon is not NULL, a successful call stores the identity of the monitor in the ErlNifMonitor struct that mon points to. That identifier is what you use to refer to the monitor later for removal with enif_demonitor_process, or to compare with enif_compare_monitors ๐
A monitor gets automatically removed when it triggers, or when the resource is deallocated. So like, it cleans up after itself, iconic.
caller_env is the environment of the calling thread (process bound or callback environment), or NULL if you're calling from a custom thread that ERTS did not spawn.
Returns 0 on success, < 0 if no down callback was provided, and > 0 if the process is no longer alive or if target_pid is undefined ๐
This function is thread-safe.
Available since OTP 20.0
enif_monotonic_time()
ErlNifTime enif_monotonic_time(
ErlNifTimeUnit time_unit);
Returns the current Erlang monotonic time. Heads up though โ negative values are, like, genuinely not uncommon here, so don't panic when you see one ๐
time_unit is the time unit of the returned value.
Returns ERL_NIF_TIME_ERROR if you call it with an invalid time unit argument, or if you call it from a thread that is not a scheduler thread.
See also ErlNifTime and ErlNifTimeUnit.
Available since OTP 18.3
enif_mutex_create()
ErlNifMutex * enif_mutex_create(
char *name);
Same as erl_drv_mutex_create.
Available since OTP R13B04
enif_mutex_destroy()
void enif_mutex_destroy(
ErlNifMutex *mtx);
Same as erl_drv_mutex_destroy.
Available since OTP R13B04
enif_mutex_lock()
void enif_mutex_lock(
ErlNifMutex *mtx);
Same as erl_drv_mutex_lock.
Available since OTP R13B04
enif_mutex_name()
char* enif_mutex_name(
ErlNifMutex* mtx);
Same as erl_drv_mutex_name.
Available since OTP 21.0
enif_mutex_trylock()
int enif_mutex_trylock(
ErlNifMutex *mtx);
Same as erl_drv_mutex_trylock.
Available since OTP R13B04
enif_mutex_unlock()
void enif_mutex_unlock(
ErlNifMutex *mtx);
Same as erl_drv_mutex_unlock.
Available since OTP R13B04
enif_now_time()
ERL_NIF_TERM enif_now_time(
ErlNifEnv *env);
Returns an erlang:now() time stamp.
๐จ This function is deprecated. It's giving legacy, bestie. Don't build new stuff on it.
Available since OTP 19.0
enif_open_resource_type()
ErlNifResourceType * enif_open_resource_type(
ErlNifEnv* env,
const char* module_str,
const char* name,
ErlNifResourceDtor* dtor,
ErlNifResourceFlags flags,
ErlNifResourceFlags* tried);
Creates โ or takes over โ a resource type identified by the string name, and gives it the destructor function that dtor points to โจ
flags can have these values:
ERL_NIF_RT_CREATEโ makes a brand new resource type that doesn't already exist.ERL_NIF_RT_TAKEOVERโ opens an existing resource type and takes over ownership of all its instances. Thedtoryou supply gets called both for existing instances and for new instances not yet created by the calling NIF library.
Those two flag values can be combined with bitwise OR ๐
The resource type name is local to the calling module. The module_str argument is not (yet) used and must be NULL. And dtor can be NULL if no destructor is needed โ no destructor, no problem.
On success, the function returns a pointer to the resource type, and *tried is set to either ERL_NIF_RT_CREATE or ERL_NIF_RT_TAKEOVER to show you what actually went down. On failure, it returns NULL and sets *tried to flags. It is allowed to set tried to NULL. ๐
โ ๏ธ Notice thatenif_open_resource_typeis only allowed to be called in the two callbacksloadandupgrade. The resource type is only created or taken over if the callingload/upgradefunction returns successfully. Like, timing matters here, bestie.
See also enif_open_resource_type_x.
Available since OTP R13B04
enif_open_resource_type_x()
ErlNifResourceType * enif_open_resource_type_x(
ErlNifEnv* env,
const char* name,
const ErlNifResourceTypeInit* init,
ErlNifResourceFlags flags,
ErlNifResourceFlags* tried);
Same as enif_open_resource_type, except it also accepts extra callback functions for resource types that get used together with enif_select and enif_monitor_process ๐ฆ
init is a pointer to an ErlNifResourceTypeInit structure containing the function pointers for the destructor, down and stop callbacks for the resource type.
๐ NOTE: Only the membersdtor,downandstopinErlNifResourceTypeInitare read byenif_open_resource_type_x. If you wanna implement the newdyncallcallback, useenif_init_resource_typeinstead. iykyk ๐
Available since OTP 20.0
enif_init_resource_type()
ErlNifResourceType * enif_init_resource_type(
ErlNifEnv* env,
const char* name,
const ErlNifResourceTypeInit* init,
ErlNifResourceFlags flags,
ErlNifResourceFlags* tried);
Same as enif_open_resource_type_x, except it accepts one additional callback function for resource types that are used together with enif_dynamic_resource_call ๐
init is a pointer to an ErlNifResourceTypeInit structure that contains the callback function pointers dtor, down, stop and the new dyncall. The struct also contains the field members that must be set to the number of initialized callbacks counted from the top of the struct. So like, for example, to initialize all callbacks including dyncall, the members should be set to 4. All callbacks are optional and may be set to NULL โ mix and match, bestie ๐
Available since OTP 24.0
enif_port_command()
int enif_port_command(
ErlNifEnv* env, const
ErlNifPort* to_port,
ErlNifEnv *msg_env,
ERL_NIF_TERM msg);
Works exactly like erlang:port_command/2, except that it is always completely asynchronous. It does not wait around, it does not text back, it just goes โจ
envโ the environment of the calling process. Must not beNULL๐ซ*to_portโ the port ID of the receiving port. The port ID is to refer to a port on the local node.msg_envโ the environment of the message term. Can be a process independent environment allocated withenif_alloc_env, orNULL.msgโ the message term to send. The same limitations apply as on the payload toerlang:port_command/2.
Using a msg_env of NULL is an optimization that groups together calls to enif_alloc_env, enif_make_copy, enif_port_command, and enif_free_env into one single call ๐ฎ That optimization is only useful when a majority of the terms are to be copied from env to msg_env. Otherwise it's giving pointless, ngl.
Returns true if the command is successfully sent. Returns false if the command fails, for example:
*to_portdoes not refer to a local port.- The currently executing process (that is, the sender) is not alive.
msgis invalid.
See also enif_get_local_port.
Available since OTP 19.0
enif_priv_data()
void * enif_priv_data(
ErlNifEnv* env);
Returns the pointer to the private data that was set by load or upgrade ๐ Your lil stash, right where you left it.
Available since OTP R13B04
enif_raise_exception()
ERL_NIF_TERM enif_raise_exception(
ErlNifEnv* env,
ERL_NIF_TERM reason);
Creates an error exception with the term reason to be returned from a NIF, and associates it with environment env ๐ค
And here's the powerful part: once a NIF โ or any function it calls โ invokes enif_raise_exception, the runtime ensures that the exception it creates is raised when the NIF returns, even if the NIF attempts to return a non-exception term instead. Like, you can't escape it. Periodt ๐
The return value from enif_raise_exception can only be used as the return value from the NIF that invoked it (directly or indirectly), or be passed to enif_is_exception. It can not be passed to any other NIF API function. Read that again, bestie ๐
See also enif_has_pending_exception and enif_make_badarg.
Available since OTP 18.0
enif_realloc()
void * enif_realloc(
void* ptr,
size_t size);
Reallocates memory that was allocated by enif_alloc to size bytes. Glow-up for your buffer โจ
Returns NULL if the reallocation fails.
The returned pointer is suitably aligned for any built-in type that fits in the allocated memory. So alignment is handled, you don't gotta worry ๐ซถ
Available since OTP 20.2
enif_realloc_binary()
int enif_realloc_binary(
ErlNifBinary* bin,
size_t size);
Changes the size of a binary bin. The source binary can be read-only, in which case it is left untouched and a mutable copy is allocated and assigned to *bin ๐ธ Like, it respects the original and gives you a fresh new version to play with. Iconic.
Okay so โ true when it went fine, false if the memory allocation ghosted us ๐ญ
Available since OTP R13B04 โจ
enif_release_binary()</p> ๐
void enif_release_binary(
ErlNifBinary* bin);
Releases a binary you grabbed from enif_alloc_binary. say bye bestie, it's gone ๐
enif_release_resource()</p> ๐ฆ
void enif_release_resource(
void* obj);
Drops a reference to the resource object obj that you got from enif_alloc_resource. The resource object gets destructed the moment the last reference dips out ๐ซถ. Every single call to enif_release_resource has to match up with an earlier call to enif_alloc_resource or enif_keep_resource โ like, one in, one out, no cap. and heads up, references created by enif_make_resource can only be removed by the garbage collector, that's just the rules ๐.
There are no guarantees about exactly when the destructor of an unreferenced resource gets called. Like, it could be called directly by enif_release_resource, or it could be scheduled to run later โ possibly on a whole other thread ๐. Either way, don't be out here assuming timing.
Available since OTP R13B04 โจ
enif_rwlock_create()</p> ๐
ErlNifRWLock * enif_rwlock_create(
char *name);
Same as erl_drv_rwlock_create. ๐
Available since OTP R13B04 โจ
enif_rwlock_destroy()</p> ๐๏ธ
void enif_rwlock_destroy(
ErlNifRWLock *rwlck);
Same as erl_drv_rwlock_destroy. ๐
Available since OTP R13B04 โจ
enif_rwlock_name()</p> ๐ท๏ธ
char* enif_rwlock_name(
ErlNifRWLock* rwlck);
Same as erl_drv_rwlock_name. ๐
Available since OTP 21.0 โจ
enif_rwlock_rlock()</p> ๐
void enif_rwlock_rlock(
ErlNifRWLock *rwlck);
Same as erl_drv_rwlock_rlock. ๐
Available since OTP R13B04 โจ
enif_rwlock_runlock()</p> ๐
void enif_rwlock_runlock(
ErlNifRWLock *rwlck);
Same as erl_drv_rwlock_runlock. ๐
Available since OTP R13B04 โจ
enif_rwlock_rwlock()</p> โ๏ธ
void enif_rwlock_rwlock(
ErlNifRWLock *rwlck);
Same as erl_drv_rwlock_rwlock. ๐
Available since OTP R13B04 โจ
enif_rwlock_rwunlock()</p> ๐ช
void enif_rwlock_rwunlock(
ErlNifRWLock *rwlck);
Same as erl_drv_rwlock_rwunlock. ๐
Available since OTP R13B04 โจ
enif_rwlock_tryrlock()</p> ๐ฏ
int enif_rwlock_tryrlock(
ErlNifRWLock *rwlck);
Same as erl_drv_rwlock_tryrlock. ๐
Available since OTP R13B04 โจ
enif_rwlock_tryrwlock()</p> ๐ฏ
int enif_rwlock_tryrwlock(
ErlNifRWLock *rwlck);
Same as erl_drv_rwlock_tryrwlock. ๐
Available since OTP R13B04 โจ
enif_schedule_nif()</p> โฐ
ERL_NIF_TERM enif_schedule_nif(
ErlNifEnv* caller_env,
const char* fun_name,
int flags,
ERL_NIF_TERM (*fp)(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]),
int argc,
const ERL_NIF_TERM argv[]);
Schedules the NIF fp to execute. This one is the moment bestie ๐
โ it lets your app chop up long-running work into a bunch of regular NIF calls, or schedule a dirty NIF to run over on a dirty scheduler thread. iconic behaviour, honestly.
caller_envโ Must be a process bound environment of the calling NIF.fun_nameโ Gives a name to the NIF that's being scheduled for execution. If it can't be converted to an atom,enif_schedule_nifreturns abadargexception. so like, name it something real ๐flagsโ Must be set to0for a regular NIF,ERL_NIF_DIRTY_JOB_CPU_BOUNDif the job is expected to be CPU-bound, orERL_NIF_DIRTY_JOB_IO_BOUNDfor jobs that will be I/O-bound.argcandargvโ Can either be the originals passed into the calling NIF, or values created by the calling NIF. your call, boo.
The calling NIF must use the return value of enif_schedule_nif as its own return value. that's not optional, that's the whole assignment ๐
And be aware โ enif_schedule_nif, as its name is literally telling you, only schedules the NIF for future execution. The calling NIF does not block waiting around for the scheduled NIF to execute and return. Which means the calling NIF cannot expect to receive the scheduled NIF's return value and use it for further operations. it's giving "sent it, don't text back" energy ๐
Available since OTP 17.3 โจ
enif_select()</p> ๐ง
int enif_select(
ErlNifEnv* env,
ErlNifEvent event,
enum ErlNifSelectFlags mode,
void* obj,
const ErlNifPid* pid,
ERL_NIF_TERM ref);
This function can be used to receive asynchronous notifications when OS-specific event objects become ready for either read or write operations. the OS pings you when it's ready, and you handle it ๐ซถ
Argument event identifies the event object. On Unix systems, the functions select/poll are used. The event object must be a socket, pipe or other file descriptor object that select/poll can use. no random stuff, fr fr.
Argument mode describes the type of events to wait for. It can be ERL_NIF_SELECT_READ, ERL_NIF_SELECT_WRITE or a bitwise OR combination to wait for both. It can also be ERL_NIF_SELECT_STOP or ERL_NIF_SELECT_CANCEL which are described further below. When a read or write event is triggered, a notification message like this is sent to the process identified by pid:
{select, Obj, Ref, ready_input | ready_output}
ready_input or ready_output indicates if the event object is ready for reading or writing.
NOTE: For complete control over the message format use the newer functionsenif_select_readorenif_select_writeintroduced inerts-11.0(OTP-22.0). โจ
Argument pid may be NULL to indicate the calling process. It must not be set as undefined. like, don't do that. just don't ๐
Argument obj is a resource object obtained from enif_alloc_resource. The purpose of the resource objects is as a container of the event object โ to manage its state and lifetime. A handle to the resource is received in the notification message as Obj.
Argument ref must be either a reference obtained from erlang:make_ref/0 or the atom undefined. It will be passed as Ref in the notifications. If a selective receive statement is used to wait for the notification, then a reference created just before the receive will exploit a runtime optimization that bypasses all earlier received messages in the queue. look at that, tiny speed hack ๐ง
The notifications are one-shot only ๐ฏ. To receive further notifications of the same type (read or write), repeated calls to enif_select must be made after receiving each notification. one and done, no subscription bestie.
ERL_NIF_SELECT_CANCEL can be used to cancel previously selected events. It must be used in a bitwise OR combination with ERL_NIF_SELECT_READ and/or ERL_NIF_SELECT_WRITE to indicate which type of event to cancel. Arguments pid and ref are ignored when ERL_NIF_SELECT_CANCEL is specified. The return value will tell you if the event was actually cancelled or if a notification may already have been sent. ๐ซ
Use ERL_NIF_SELECT_STOP as mode in order to safely close an event object that has been passed to enif_select. The stop callback of the resource obj will be called when it is safe to close the event object. This safe way of closing event objects must be used even if all notifications have been received (or cancelled) and no further calls to enif_select have been made. ERL_NIF_SELECT_STOP will first cancel any selected events before it calls or schedules the stop callback. Arguments pid and ref are ignored when ERL_NIF_SELECT_STOP is specified. do it the safe way, always ๐
The first call to enif_select for a specific OS event will establish a relation between the event object and the containing resource. All subsequent calls for an event must pass its containing resource as argument obj. The relation is dissolved when enif_select has been called with mode as ERL_NIF_SELECT_STOP and the corresponding stop callback has returned. A resource can contain several event objects but one event object can only be contained within one resource. A resource will not be destructed until all its contained relations have been dissolved.
NOTE: Useenif_monitor_processtogether withenif_selectto detect failing Erlang processes and prevent them from causing permanent leakage of resources and their contained OS event objects. ๐๐๐ leaking is not the vibe.
Returns a non-negative value on success where the following bits can be set:
ERL_NIF_SELECT_STOP_CALLEDโ The stop callback was called directly byenif_select.ERL_NIF_SELECT_STOP_SCHEDULEDโ The stop callback was scheduled to run on some other thread or later by this thread.ERL_NIF_SELECT_READ_CANCELLEDโ A read event was cancelled byERL_NIF_SELECT_CANCELorERL_NIF_SELECT_STOPand is guaranteed not to generate aready_inputnotification message.ERL_NIF_SELECT_WRITE_CANCELLEDโ A write event was cancelled byERL_NIF_SELECT_CANCELorERL_NIF_SELECT_STOPand is guaranteed not to generate aready_outputnotification message.
Returns a negative value if the call failed where the following bits can be set:
ERL_NIF_SELECT_INVALID_EVENTโ Argumenteventis not a valid OS event object.ERL_NIF_SELECT_FAILEDโ The system call failed to add the event object to the poll set.
NOTE: Use bitwise AND to test for specific bits in the return value. New significant bits may be added in future releases to give more detailed information for both failed and successful calls. Do NOT use equality tests like ==, as that may cause your application to stop working. ๐จ seriously, don't. Example:
retval = enif_select(env, fd, ERL_NIF_SELECT_STOP, resource, ref);
if (retval < 0) {
/* handle error */
}
/* Success! */
if (retval & ERL_NIF_SELECT_STOP_CALLED) {
/* ... */
}
NOTE: ThemodeflagERL_NIF_SELECT_CANCELand the return flagsERL_NIF_SELECT_READ_CANCELLEDandERL_NIF_SELECT_WRITE_CANCELLEDwere introduced inerts-11.0(OTP-22.0). ๐
Available since OTP 20.0 โจ
enif_select_read()</p> ๐จ
Available since OTP 22.0 โจ
enif_select_write()</p> ๐ฎ
int enif_select_read(
ErlNifEnv* env,
ErlNifEvent event,
void* obj,
const ErlNifPid* pid,
ERL_NIF_TERM msg,
ErlNifEnv* msg_env);
int enif_select_write(
ErlNifEnv* env,
ErlNifEvent event,
void* obj,
const ErlNifPid* pid,
ERL_NIF_TERM msg,
ErlNifEnv* msg_env);
These are variants of enif_select where you can supply your own message term msg that will be sent to the process instead of the predefined tuple {select,_,_,_}. custom message, custom slay ๐
Argument msg_env must either be NULL or the environment of msg allocated with enif_alloc_env. If argument msg_env is NULL, the term msg will be copied โ otherwise both msg and msg_env will be invalidated by a successful call to enif_select_read or enif_select_write. The environment is then to either be freed with enif_free_env or cleared for reuse with enif_clear_env. An unsuccessful call will leave msg and msg_env still valid. okay so like, one of those two things is gonna happen and you gotta know which ๐ซถ
Apart from the message format, enif_select_read and enif_select_write behave exactly the same as enif_select with argument mode as either ERL_NIF_SELECT_READ or ERL_NIF_SELECT_WRITE. To cancel or close events, use enif_select ๐
Available since OTP 22.0 โจ
enif_self() ๐ช
ErlNifPid * enif_self(
ErlNifEnv* caller_env,
ErlNifPid* pid);
Initializes the ErlNifPid variable at *pid so it represents the calling process.
Returns pid if it works, or NULL if caller_env is not a process bound environment. no cap, that's the whole vibe check ๐ญ
Available since OTP R14B ๐ธ
enif_send() ๐จ
int enif_send(
ErlNifEnv* caller_env,
ErlNifPid* to_pid,
ErlNifEnv* msg_env,
ERL_NIF_TERM msg);
Sends a message to a process. slay, the classic โจ
caller_env : The environment of the calling thread (process bound or callback environment), or NULL if you're calling from a custom thread that was not spawned by ERTS.
to_pid : The pid of the receiving process. This pid has to refer to a process on the local node btw.
msg_env : The environment of the message term. Must be a process independent environment allocated with enif_alloc_env, or NULL.
msg : The message term to send.
Returns true if the message got sent successfully. Returns false if the send operation fails, that is:
*to_piddoes not refer to an alive local process.- The currently executing process (that is, the sender) is not alive. ๐ญ
The message environment msg_env with all its terms (including msg) is invalidated by a successful call to enif_send. You're then supposed to either free the environment with enif_free_env or clear it for reuse with enif_clear_env. An unsuccessful call will leave msg and msg_env still valid, phew ๐ซถ
If msg_env is set to NULL, the msg term is copied, and the original term and its environment are still valid after the call.
This function is thread-safe ๐
NOTE: Passingmsg_envasNULLis only supported as from ERTS 8.0 (Erlang/OTP 19).
Available since OTP R14B โญ
enif_set_option() โ๏ธ
int enif_set_option(
ErlNifEnv *env,
ErlNifOption opt,
...);
Set an option. On success, zero will be returned. On failure, a non-zero value will be returned. Currently the following options can be set:
ERL_NIF_OPT_DELAY_HALT
enif_set_option(env, ERL_NIF_OPT_DELAY_HALT)
Enable delay of runtime system halt with flushing enabled until all calls to NIFs in the NIF library have returned. If the delay halt feature has not been enabled, a halt with flushing enabled may complete even though processes are still executing inside NIFs in the NIF library. Note that by "returning" we here mean the first point where the NIF returns control back to the runtime system, and not the point where a call to a NIF returns a value back to the Erlang code that called the NIF. That is, if you schedule execution of a NIF, using enif_schedule_nif(), from within a NIF while the system is halting, the scheduled NIF call will not be executed even though delay halt has been enabled for the NIF library.
The runtime system halts when one of the erlang:halt() BIFs are called. By default flushing is enabled, but can be disabled using the erlang:halt/2 BIF. When flushing has been disabled, the delay halt setting will have no effect. That is, the runtime system will halt without waiting for NIFs to return even if the delay halt setting has been enabled. See the {flush, boolean()} option of erlang:halt/2 for more information.
The ERL_NIF_OPT_DELAY_HALT option can only be set during loading of a NIF library, in a call to enif_set_option() inside a NIF library load() or upgrade() call, and will fail if set somewhere else. The env argument must be the callback environment passed to the load() or the upgrade() call. This option can also only be set once. That is, the delay halt setting cannot be changed once it has been enabled. The delay halt setting is tied to the module instance with which the NIF library instance has been loaded. That is, in case both a new and old version of a module using the NIF library are loaded, they can have the same or different delay halt settings.
The delay halt feature can be used in combination with an on halt callback. The on halt callback is in this case typically used to notify processes blocked in NIFs in the library that it is time to return in order to let the runtime system complete the halting. Such NIFs should be dirty NIFs, since ordinary NIFs should never block for a long time. ๐
ERL_NIF_OPT_ON_HALT
enif_set_option(env, ERL_NIF_OPT_ON_HALT, on_halt)
Install a callback that will be called when the runtime system halts with flushing enabled.
The runtime system halts when one of the erlang:halt() BIFs are called. By default flushing is enabled, but can be disabled using the erlang:halt/2 BIF. When flushing has been disabled, the runtime system will halt without calling any on halt callbacks even if such are installed. See the {flush, boolean()} option of erlang:halt/2 for more information.
The ERL_NIF_OPT_ON_HALT option can only be set during loading of a NIF library in a call to enif_set_option() inside a NIF library load() or upgrade() call, and will fail if called somewhere else. The env argument must be the callback environment passed to the load() or the upgrade() call. The on_halt argument should be a function pointer to the callback to install.
The on_halt callback will be tied to the module instance with which the NIF library instance has been loaded. That is, in case both a new and old version of a module using the NIF library are loaded, they can both have different, none, or the same on halt callbacks installed. When unloading the NIF library during a code purge, an installed on halt callback will be uninstalled. The ERL_NIF_OPT_ON_HALT option can also only be set once. That is, the on halt callback cannot be changed or removed once it has been installed, by any other means than purging the module instance that loaded the NIF library. ๐ค
When the installed on halt callback is called, it will be passed a pointer to priv_data as argument. The priv_data pointer can be set when loading the NIF library.
The on halt callback can be used in combination with delay of halt until all calls into the library have returned. The on halt callback is in this case typically used to notify processes blocked in NIFs in the library that it is time to return in order to let the runtime system complete the halting. Such NIFs should be dirty NIFs, since ordinary NIFs should never block for a long time.
ERL_NIF_OPT_ON_UNLOAD_THREAD
enif_set_option(env, ERL_NIF_OPT_ON_UNLOAD_THREAD, on_unload_thread)
Install a callback that will be called by each scheduler thread when the module instance that the NIF library belongs to is purged as old. A typical use is to release thread specific data. ๐งต
The ERL_NIF_OPT_ON_UNLOAD_THREAD option can only be set during loading of a NIF library inside a call to load() or upgrade(), and will fail if called somewhere else. The env argument must be the callback environment passed to the load() or the upgrade() call.
The on_unload_thread argument should be a function pointer to the callback to install. The on_unload_thread callback will be tied to the module instance with which the NIF library instance has been loaded. That is, in case both a new and old version of a module using the NIF library are loaded, they can both have different, none, or the same on_unload_thread callbacks installed. The ERL_NIF_OPT_ON_UNLOAD_THREAD option can only be set once and cannot be changed or removed once it has been installed for a module instance.
When the installed on_unload_thread callback is called, it will be passed a pointer to priv_data as argument. The priv_data pointer can be set when loading the NIF library.
The calls to the on_unload_thread function are made concurrently by the different scheduler threads. There is no synchronization enforced between the threads. However, the single finalizing call to the unload() callback for the module instance will not be made until all calls to on_unload_thread have returned. fr fr, that's the deal ๐ค
Available since OTP 26.0 โจ
enif_set_pid_undefined() ๐ซ
void enif_set_pid_undefined(
ErlNifPid* pid);
Sets an ErlNifPid variable as undefined. See enif_is_pid_undefined.
Available since OTP 22.0 ๐ธ
enif_term_size() ๐
unsigned enif_term_size(
ERL_NIF_TERM term);
Gets the number of bytes used to store term. The size does not include ERL_NIF_TERM itself, or binary data held by the term. iykyk ๐
Available since OTP 29.0 โญ
enif_sizeof_resource() ๐งฎ
unsigned enif_sizeof_resource(
void* obj);
Gets the byte size of resource object obj obtained by enif_alloc_resource.
Available since OTP R13B04 ๐
enif_snprintf() ๐จ๏ธ
int enif_snprintf(
char *str,
size_t size,
const char *format,
...);
Similar to snprintf, but this format string also accepts "%T", which formats Erlang terms of type ERL_NIF_TERM. ๐
This function is primarily intended for debugging purposes. It is not recommended to print very large terms with %T. The function may change errno, even if successful. Not me getting side effects from a printf bestie ๐ญ
Available since OTP 19.0 โจ
enif_system_info() ๐ฅ๏ธ
void enif_system_info(
ErlNifSysInfo *sys_info_ptr,
size_t size);
Same as driver_system_info.
Available since OTP R13B04 ๐
enif_term_to_binary() ๐
int enif_term_to_binary(
ErlNifEnv *env,
ERL_NIF_TERM term,
ErlNifBinary *bin);
Allocates a new binary with enif_alloc_binary and stores the result of encoding term according to the Erlang external term format. the way that it just encodes for you โจ
Returns true on success, or false if the allocation fails. ๐ฌ
See also erlang:term_to_binary/1 and enif_binary_to_term.
Available since OTP 19.0 ๐
enif_term_type() ๐
ErlNifTermType enif_term_type(
ErlNifEnv *env,
ERL_NIF_TERM term);
Determines the type of the given term. The term must be an ordinary Erlang term and not one of the special terms returned by enif_raise_exception, enif_schedule_nif, or similar. so like, actual terms only pls ๐
The following types are defined at the moment:
ERL_NIF_TERM_TYPE_ATOMERL_NIF_TERM_TYPE_BITSTRINGโ a bitstring or a binary ๐ERL_NIF_TERM_TYPE_FLOATโ it's giving floatERL_NIF_TERM_TYPE_FUNโ a fun, bestieERL_NIF_TERM_TYPE_INTEGERโ the integer of it allERL_NIF_TERM_TYPE_LISTโ a list, empty or not, she doesn't judgeERL_NIF_TERM_TYPE_MAPโ map core energyERL_NIF_TERM_TYPE_PIDโ a pid, iconicERL_NIF_TERM_TYPE_PORTโ a portERL_NIF_TERM_TYPE_REFERENCEโ a referenceERL_NIF_TERM_TYPE_TUPLEโ a tuple, periodt
ok so real talk: new types may be added in the future, so the caller must be prepared to handle unknown types. like, don't be shocked when the family grows. ๐
Available since OTP 22.0 โจ
๐ enif_thread_create()
int enif_thread_create(
char *name,
ErlNifTid *tid,
void * (*func)(void *),
void *args,
ErlNifThreadOpts *opts);
Literally the same as erl_drv_thread_create. Same energy, same rules. ๐ซถ
Available since OTP R13B04
๐ enif_thread_exit()
void enif_thread_exit(
void *resp);
Same as erl_drv_thread_exit. That's the whole vibe. ๐ฆ
Available since OTP R13B04
๐ enif_thread_join()
int enif_thread_join(
ErlNifTid tid,
void **respp);
Same as erl_drv_thread_join. No notes, she said what she said. ๐
Available since OTP R13B04
๐ enif_thread_name()
char* enif_thread_name(
ErlNifTid tid);
Same as erl_drv_thread_name. ๐
Available since OTP 21.0
๐ enif_thread_opts_create()
ErlNifThreadOpts * enif_thread_opts_create(
char *name);
Same as erl_drv_thread_opts_create. Bestie behaviour, honestly. ๐ธ
Available since OTP R13B04
๐ enif_thread_opts_destroy()
void enif_thread_opts_destroy(
ErlNifThreadOpts *opts);
Same as erl_drv_thread_opts_destroy. Clean up after yourself, queen. ๐ง
Available since OTP R13B04
๐ enif_thread_self()
ErlNifTid enif_thread_self(void);
Same as erl_drv_thread_self. Main character identification, fr fr. ๐
Available since OTP R13B04
๐ enif_thread_type()
int enif_thread_type(void);
This one figures out the type of the currently executing thread. A positive value means it's a scheduler thread, while a negative value or zero means it's another type of thread. Currently the following specific types exist (and yes, they may be extended in the future, so don't get too comfy):
ERL_NIF_THR_UNDEFINEDโ undefined thread that is not a scheduler thread. lowkey mysterious.ERL_NIF_THR_NORMAL_SCHEDULERโ a normal scheduler thread. the standard icon. โญERL_NIF_THR_DIRTY_CPU_SCHEDULERโ a dirty CPU scheduler thread. highkey busy. ๐ฅERL_NIF_THR_DIRTY_IO_SCHEDULERโ a dirty I/O scheduler thread. she's doing the most. ๐
Available since OTP 19.0
๐ enif_time_offset()
ErlNifTime enif_time_offset(
ErlNifTimeUnit time_unit);
Returns the current time offset between Erlang monotonic time and Erlang system time, converted into the time_unit passed as argument. ๐ฐ๏ธ
time_unit is the time unit of the returned value, obviously bestie.
Returns ERL_NIF_TIME_ERROR if it's called with an invalid time unit argument, or if it's called from a thread that is not a scheduler thread. Like, read the room, this function has requirements. ๐ญ
See also ErlNifTime and ErlNifTimeUnit.
Available since OTP 18.3
๐ enif_tsd_get()
void * enif_tsd_get(
ErlNifTSDKey key);
Same as erl_drv_tsd_get. ๐
Available since OTP R13B04
๐ enif_tsd_key_create()
int enif_tsd_key_create(
char *name,
ErlNifTSDKey *key);
Same as erl_drv_tsd_key_create. Making keys, very responsible of you. ๐
Available since OTP R13B04
๐ enif_tsd_key_destroy()
void enif_tsd_key_destroy(
ErlNifTSDKey key);
Same as erl_drv_tsd_key_destroy. ๐
Available since OTP R13B04
๐ enif_tsd_set()
void enif_tsd_set(
ErlNifTSDKey key,
void *data);
Same as erl_drv_tsd_set. ๐
Available since OTP R13B04
๐ enif_vfprintf()
int enif_vfprintf(
FILE *stream,
const char *format,
va_list ap);
Equivalent to enif_fprintf except that it's called with a va_list instead of a variable number of arguments. Same output, different plumbing. ๐
Available since OTP 21.0
๐ enif_vsnprintf()
int enif_vsnprintf(
char *str,
size_t size,
const char *format,
va_list ap);
Equivalent to enif_snprintf except that it's called with a va_list instead of a variable number of arguments. The va_list of it all, honestly. โจ
Available since OTP 21.0
๐ enif_whereis_pid()
int enif_whereis_pid(
ErlNifEnv *caller_env,
ERL_NIF_TERM name,
ErlNifPid *pid);
Looks up a process by its registered name. She's doing the searching so you don't have to. ๐
caller_envโ the environment of the calling thread (process bound or callback environment) orNULLif calling from a custom thread not spawned by ERTS.nameโ the name of a registered process, as an atom.*pidโ theErlNifPidin which the resolved process id is stored.
On success, sets *pid to the local process registered with name and returns true. If name is not a registered process, or is not an atom, false is returned and *pid is unchanged (she does not touch your stuff unless she's sure, we love boundaries ๐ซถ).
Works as erlang:whereis/1, but restricted to processes. See enif_whereis_port to resolve registered ports.
Available since OTP 20.0
๐ enif_whereis_port()
int enif_whereis_port(
ErlNifEnv *caller_env,
ERL_NIF_TERM name,
ErlNifPort *port);
Looks up a port by its registered name. Same energy, different target. ๐
caller_envโ the environment of the calling thread (process bound or callback environment) orNULLif calling from a custom thread not spawned by ERTS.nameโ the name of a registered port, as an atom.*portโ theErlNifPortin which the resolved port id is stored.
On success, sets *port to the port registered with name and returns true. If name is not a registered port, or is not an atom, false is returned and *port is unchanged. No cap. ๐ธ
Works as erlang:whereis/1, but restricted to ports. See enif_whereis_pid to resolve registered processes.
Available since OTP 20.0
๐ See Also โจ
erlang:load_nif/2- NIFs (tutorial)
- Debugging NIFs and Port Drivers
ok bestie that's the whole entire page, we ATE and left absolutely zero crumbs ๐ ๐โจ
and before you close the tab โ this absolute icon of a manual is brought to you by Ericsson AB, sitting pretty at erts 17.0.6 (like, erl_nif(3), section 3, you know the one). go forth and write NIFs responsibly, queen. ๐ซถ๐๐
๐ฆ where this page comes from
- ubuntu stonking: erlang-doc 1:29.0.6+dfsg-1 ยท Apache-2.0
- ๐ girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms