1erl_nif(3)                    C Library Functions                   erl_nif(3)
2
3
4

NAME

6       erl_nif - API functions for an Erlang NIF library.
7

DESCRIPTION

9       A  NIF  library  contains native implementation of some functions of an
10       Erlang module. The native implemented functions (NIFs) are called  like
11       any other functions without any difference to the caller. Each NIF must
12       have an implementation in Erlang that is invoked  if  the  function  is
13       called  before  the  NIF library is successfully loaded. A typical such
14       stub implementation is to throw an exception. But it can also  be  used
15       as  a fallback implementation if the NIF library is not implemented for
16       some architecture.
17
18   Warning:
19
20       Use this functionality with extreme care.
21
22       A native function is executed as a direct extension of the native  code
23       of  the  VM. Execution is not made in a safe environment. The VM cannot
24       provide the same services as provided when executing Erlang code,  such
25       as  pre-emptive scheduling or memory protection. If the native function
26       does not behave well, the whole VM will misbehave.
27
28         * A native function that crash will crash the whole VM.
29
30         * An erroneously implemented native function can cause a VM  internal
31           state  inconsistency, which can cause a crash of the VM, or miscel‐
32           laneous misbehaviors of the VM at any point after the call  to  the
33           native function.
34
35         * A  native  function  doing  lengthy  work before returning degrades
36           responsiveness of the  VM,  and  can  cause  miscellaneous  strange
37           behaviors.  Such strange behaviors include, but are not limited to,
38           extreme memory usage, and bad load  balancing  between  schedulers.
39           Strange  behaviors  that can occur because of lengthy work can also
40           vary between Erlang/OTP releases.
41
42       A minimal example of a NIF library can look as follows:
43
44       /* niftest.c */
45       #include <erl_nif.h>
46
47       static ERL_NIF_TERM hello(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
48       {
49           return enif_make_string(env, "Hello world!", ERL_NIF_LATIN1);
50       }
51
52       static ErlNifFunc nif_funcs[] =
53       {
54           {"hello", 0, hello}
55       };
56
57       ERL_NIF_INIT(niftest,nif_funcs,NULL,NULL,NULL,NULL)
58
59       The Erlang module can look as follows:
60
61       -module(niftest).
62
63       -export([init/0, hello/0]).
64
65       init() ->
66             erlang:load_nif("./niftest", 0).
67
68       hello() ->
69             "NIF library not loaded".
70
71       Compile and test can look as follows (on Linux):
72
73       $> gcc -fPIC -shared -o niftest.so niftest.c -I $ERL_ROOT/usr/include/
74       $> erl
75
76       1> c(niftest).
77       {ok,niftest}
78       2> niftest:hello().
79       "NIF library not loaded"
80       3> niftest:init().
81       ok
82       4> niftest:hello().
83       "Hello world!"
84
85       A better solution for a real module is to take  advantage  of  the  new
86       directive  on_load  (see  section  Running  a Function When a Module is
87       Loaded in the Erlang Reference Manual) to load the NIF library automat‐
88       ically when the module is loaded.
89
90   Note:
91       A NIF does not have to be exported, it can be local to the module. How‐
92       ever, unused local stub functions will be optimized away  by  the  com‐
93       piler, causing loading of the NIF library to fail.
94
95
96       Once loaded, a NIF library is persistent. It will not be unloaded until
97       the module code version that it belongs to is purged.
98

FUNCTIONALITY

100       All interaction between NIF code and the Erlang runtime system is  per‐
101       formed  by calling NIF API functions. Functions exist for the following
102       functionality:
103
104         Read and write Erlang terms:
105           Any Erlang terms can be passed to a NIF as function  arguments  and
106           be  returned  as  function  return  values. The terms are of C-type
107           ERL_NIF_TERM and can only be read or written using  API  functions.
108           Most functions to read the content of a term are prefixed enif_get_
109           and usually return true (or false) if the term is of  the  expected
110           type  (or  not).  The  functions  to  write  terms are all prefixed
111           enif_make_ and usually return the created ERL_NIF_TERM.  There  are
112           also   some   functions   to   query   terms,   like  enif_is_atom,
113           enif_is_identical, and enif_compare.
114
115           All terms of type ERL_NIF_TERM belong to  an  environment  of  type
116           ErlNifEnv.  The lifetime of a term is controlled by the lifetime of
117           its environment object. All API functions that read or write  terms
118           has  the environment that the term belongs to as the first function
119           argument.
120
121         Binaries:
122           Terms of type binary are accessed with the help of struct type Erl‐
123           NifBinary,  which  contains a pointer (data) to the raw binary data
124           and the length (size) of the data in bytes. Both data and size  are
125           read-only  and are only to be written using calls to API functions.
126           Instances of ErlNifBinary are, however,  always  allocated  by  the
127           user (usually as local variables).
128
129           The  raw  data  pointed  to by data is only mutable after a call to
130           enif_alloc_binary or enif_realloc_binary. All other functions  that
131           operate  on  a binary leave the data as read-only. A mutable binary
132           must in the end either be freed with  enif_release_binary  or  made
133           read-only   by   transferring   it   to   an   Erlang   term   with
134           enif_make_binary. However, it does not have to occur  in  the  same
135           NIF call. Read-only binaries do not have to be released.
136
137           enif_make_new_binary  can  be  used  as  a shortcut to allocate and
138           return a binary in the same NIF call.
139
140           Binaries are sequences of whole bytes. Bitstrings with an arbitrary
141           bit length have no support yet.
142
143         Resource objects:
144           The  use  of  resource  objects is a safe way to return pointers to
145           native data structures from a NIF. A  resource  object  is  only  a
146           block of memory allocated with enif_alloc_resource. A handle ("safe
147           pointer") to this memory block can then be returned  to  Erlang  by
148           the    use    of   enif_make_resource.   The   term   returned   by
149           enif_make_resource is opaque in nature. It can be stored and passed
150           between  processes,  but the only real end usage is to pass it back
151           as an argument to a NIF. The NIF can  then  call  enif_get_resource
152           and  get back a pointer to the memory block, which is guaranteed to
153           still be valid. A resource object is not deallocated until the last
154           handle  term  is  garbage  collected  by the VM and the resource is
155           released  with  enif_release_resource  (not  necessarily  in   that
156           order).
157
158           All  resource  objects  are  created  as instances of some resource
159           type. This makes resources from different  modules  to  be  distin‐
160           guishable.    A    resource    type    is    created   by   calling
161           enif_open_resource_type when a library is loaded. Objects  of  that
162           resource  type  can  then  later be allocated and enif_get_resource
163           verifies that the resource is of the expected type. A resource type
164           can  have  a  user-supplied destructor function, which is automati‐
165           cally called when resources of that type are  released  (by  either
166           the garbage collector or enif_release_resource). Resource types are
167           uniquely identified by a supplied name string and the name  of  the
168           implementing module.
169
170           The  following  is a template example of how to create and return a
171           resource object.
172
173         ERL_NIF_TERM term;
174         MyStruct* obj = enif_alloc_resource(my_resource_type, sizeof(MyStruct));
175
176         /* initialize struct ... */
177
178         term = enif_make_resource(env, obj);
179
180         if (keep_a_reference_of_our_own) {
181             /* store 'obj' in static variable, private data or other resource object */
182         }
183         else {
184             enif_release_resource(obj);
185             /* resource now only owned by "Erlang" */
186         }
187         return term;
188
189           Notice that once enif_make_resource creates the term to  return  to
190           Erlang,  the  code can choose to either keep its own native pointer
191           to the allocated struct and release it later, or release it immedi‐
192           ately  and  rely  only  on  the garbage collector to deallocate the
193           resource object eventually when it collects the term.
194
195           Another use of resource objects is  to  create  binary  terms  with
196           user-defined memory management. enif_make_resource_binary creates a
197           binary term that is connected to a resource object. The  destructor
198           of  the resource is called when the binary is garbage collected, at
199           which time the binary data can be released. An example of this  can
200           be  a  binary  term  consisting  of  data  from a mmap'ed file. The
201           destructor can then do munmap to release the memory region.
202
203           Resource types support upgrade in runtime by allowing a loaded  NIF
204           library  to take over an already existing resource type and by that
205           "inherit" all existing objects of that type. The destructor of  the
206           new  library is thereafter called for the inherited objects and the
207           library with the old destructor function can  be  safely  unloaded.
208           Existing  resource  objects,  of  a  module  that is upgraded, must
209           either be deleted or taken over by the new NIF library. The unload‐
210           ing  of  a  library  is  postponed  as long as there exist resource
211           objects with a destructor function in the library.
212
213         Module upgrade and static data:
214           A loaded NIF library is tied to the  Erlang  module  instance  that
215           loaded it. If the module is upgraded, the new module instance needs
216           to load its own NIF library (or maybe choose not to). The new  mod‐
217           ule  instance  can,  however,  choose  to  load  the exact same NIF
218           library as the old code if it wants to. Sharing the dynamic library
219           means that static data defined by the library is shared as well. To
220           avoid unintentionally shared static data between module  instances,
221           each Erlang module version can keep its own private data. This pri‐
222           vate data can be set when the  NIF  library  is  loaded  and  later
223           retrieved by calling enif_priv_data.
224
225         Threads and concurrency:
226           A  NIF  is thread-safe without any explicit synchronization as long
227           as it acts as a pure function and only  reads  the  supplied  argu‐
228           ments. When you write to a shared state either through static vari‐
229           ables or enif_priv_data, you need to supply your own explicit  syn‐
230           chronization.  This  includes terms in process-independent environ‐
231           ments that  are  shared  between  threads.  Resource  objects  also
232           require synchronization if you treat them as mutable.
233
234           The  library  initialization callbacks load and upgrade are thread-
235           safe even for shared state data.
236
237         Version Management:
238           When a NIF library is built, information about the NIF API  version
239           is  compiled  into  the  library. When a NIF library is loaded, the
240           runtime system verifies that the library is of  a  compatible  ver‐
241           sion. erl_nif.h defines the following:
242
243           ERL_NIF_MAJOR_VERSION:
244             Incremented when NIF library incompatible changes are made to the
245             Erlang runtime system. Normally it suffices to recompile the  NIF
246             library  when  the ERL_NIF_MAJOR_VERSION has changed, but it can,
247             under  rare  circumstances,  mean  that  NIF  libraries  must  be
248             slightly modified. If so, this will of course be documented.
249
250           ERL_NIF_MINOR_VERSION:
251             Incremented  when new features are added. The runtime system uses
252             the minor version to determine what features to use.
253
254           The runtime system normally refuses to load a NIF  library  if  the
255           major  versions  differ, or if the major versions are equal and the
256           minor version used by the NIF library is greater than the one  used
257           by  the runtime system. Old NIF libraries with lower major versions
258           are, however, allowed after a bump of the major  version  during  a
259           transition period of two major releases. Such old NIF libraries can
260           however fail if deprecated features are used.
261
262         Time Measurement:
263           Support for time measurement in NIF libraries:
264
265           * ErlNifTime
266
267           * ErlNifTimeUnit
268
269           * enif_monotonic_time()
270
271           * enif_time_offset()
272
273           * enif_convert_time_unit()
274
275         I/O Queues:
276           The Erlang nif library contains function for  easily  working  with
277           I/O  vectors  as used by the unix system call writev. The I/O Queue
278           is not thread safe, so some other synchronization mechanism has  to
279           be used.
280
281           * SysIOVec
282
283           * ErlNifIOVec
284
285           * enif_ioq_create()
286
287           * enif_ioq_destroy()
288
289           * enif_ioq_enq_binary()
290
291           * enif_ioq_enqv()
292
293           * enif_ioq_deq()
294
295           * enif_ioq_peek()
296
297           * enif_inspect_iovec()
298
299           * enif_free_iovec()
300
301           Typical usage when writing to a file descriptor looks like this:
302
303         int writeiovec(ErlNifEnv *env, ERL_NIF_TERM term, ERL_NIF_TERM *tail,
304                        ErlNifIOQueue *q, int fd) {
305
306             ErlNifIOVec vec, *iovec = &vec;
307             SysIOVec *sysiovec;
308             int saved_errno;
309             int iovcnt, n;
310
311             if (!enif_inspect_iovec(env, 64, term, tail, &iovec))
312                 return -2;
313
314             if (enif_ioq_size(q) > 0) {
315                 /* If the I/O queue contains data we enqueue the iovec and
316                    then peek the data to write out of the queue. */
317                 if (!enif_ioq_enqv(q, iovec, 0))
318                     return -3;
319
320                 sysiovec = enif_ioq_peek(q, &iovcnt);
321             } else {
322                 /* If the I/O queue is empty we skip the trip through it. */
323                 iovcnt = iovec->iovcnt;
324                 sysiovec = iovec->iov;
325             }
326
327             /* Attempt to write the data */
328             n = writev(fd, sysiovec, iovcnt);
329             saved_errno = errno;
330
331             if (enif_ioq_size(q) == 0) {
332                 /* If the I/O queue was initially empty we enqueue any
333                    remaining data into the queue for writing later. */
334                 if (n >= 0 && !enif_ioq_enqv(q, iovec, n))
335                     return -3;
336             } else {
337                 /* Dequeue any data that was written from the queue. */
338                 if (n > 0 && !enif_ioq_deq(q, n, NULL))
339                     return -4;
340             }
341
342             /* return n, which is either number of bytes written or -1 if
343                some error happened */
344             errno = saved_errno;
345             return n;
346         }
347
348         Long-running NIFs:
349           As  mentioned  in  the warning text at the beginning of this manual
350           page, it is of vital importance that a native function returns rel‐
351           atively  fast.  It  is difficult to give an exact maximum amount of
352           time that a native function is allowed to work, but usually a well-
353           behaving  native  function is to return to its caller within 1 mil‐
354           lisecond. This can be achieved using different approaches.  If  you
355           have  full control over the code to execute in the native function,
356           the best approach is to divide the work  into  multiple  chunks  of
357           work and call the native function multiple times. This is, however,
358           not  always  possible,  for  example   when   calling   third-party
359           libraries.
360
361           The  enif_consume_timeslice()  function  can  be used to inform the
362           runtime system about the length of the NIF call.  It  is  typically
363           always to be used unless the NIF executes very fast.
364
365           If  the NIF call is too lengthy, this must be handled in one of the
366           following ways to avoid  degraded  responsiveness,  scheduler  load
367           balancing problems, and other strange behaviors:
368
369           Yielding NIF:
370             If  the  functionality of a long-running NIF can be split so that
371             its work can be achieved through a series of shorter  NIF  calls,
372             the application has two options:
373
374             * Make that series of NIF calls from the Erlang level.
375
376             * Call  a  NIF  that  first  performs  a  chunk of the work, then
377               invokes the enif_schedule_nif function to schedule another  NIF
378               call  to  perform  the  next chunk. The final call scheduled in
379               this manner can then return the overall result.
380
381             Breaking up a long-running function in this manner enables the VM
382             to regain control between calls to the NIFs.
383
384             This  approach  is  always  preferred over the other alternatives
385             described below. This both from a performance perspective  and  a
386             system characteristics perspective.
387
388           Threaded NIF:
389             This  is  accomplished  by dispatching the work to another thread
390             managed by the NIF library, return from the NIF, and wait for the
391             result. The thread can send the result back to the Erlang process
392             using enif_send. Information about thread primitives is  provided
393             below.
394
395           Dirty NIF:
396
397
398       Note:
399           Dirty NIF support is available only when the emulator is configured
400           with dirty scheduler support. As of ERTS version 9.0, dirty  sched‐
401           uler  support  is enabled by default on the runtime system with SMP
402           support. The Erlang runtime without SMP support  does  not  support
403           dirty  schedulers  even when the dirty scheduler support is explic‐
404           itly enabled. To check at runtime for the presence of dirty  sched‐
405           uler threads, code can use the enif_system_info() API function.
406
407
408             A NIF that cannot be split and cannot execute in a millisecond or
409             less is called a "dirty NIF", as it performs work that the  ordi‐
410             nary  schedulers  of  the  Erlang  runtime  system  cannot handle
411             cleanly. Applications that make use of such functions must  indi‐
412             cate  to  the runtime that the functions are dirty so they can be
413             handled specially. This is handled by executing dirty jobs  on  a
414             separate  set  of schedulers called dirty schedulers. A dirty NIF
415             executing on a dirty scheduler does not have  the  same  duration
416             restriction as a normal NIF.
417
418             It  is  important to classify the dirty job correct. An I/O bound
419             job should be classified as such, and a CPU bound job  should  be
420             classified  as such. If you should classify CPU bound jobs as I/O
421             bound jobs, dirty I/O schedulers  might  starve  ordinary  sched‐
422             ulers.  I/O  bound  jobs are expected to either block waiting for
423             I/O, and/or spend a limited amount of time moving data.
424
425             To schedule a dirty NIF for execution, the  application  has  two
426             options:
427
428             * Set  the  appropriate flags value for the dirty NIF in its Erl‐
429               NifFunc entry.
430
431             * Call enif_schedule_nif, pass to it a pointer to the  dirty  NIF
432               to  be  executed,  and  indicate with argument flags whether it
433               expects the operation to be CPU-bound or I/O-bound.
434
435             A job that alternates between I/O bound  and  CPU  bound  can  be
436             reclassified  and  rescheduled using enif_schedule_nif so that it
437             executes on the correct type of dirty scheduler at all times. For
438             more information see the documentation of the erl(1) command line
439             arguments +SDcpu, and +SDio.
440
441             While a process executes a dirty NIF, some operations that commu‐
442             nicate  with it can take a very long time to complete. Suspend or
443             garbage collection of a process executing a dirty NIF  cannot  be
444             done  until  the  dirty  NIF  has returned. Thus, other processes
445             waiting for such operations to complete might have to wait for  a
446             very  long  time.  Blocking  multi-scheduling,  that  is, calling
447             erlang:system_flag(multi_scheduling, block), can also take a very
448             long  time  to complete. This becaue all ongoing dirty operations
449             on all dirty schedulers must complete before the block  operation
450             can complete.
451
452             Many  operations  communicating  with a process executing a dirty
453             NIF can, however, complete while it executes the dirty  NIF.  For
454             example,     retrieving     information    about    it    through
455             erlang:process_info, setting its group leader,  register/unregis‐
456             ter its name, and so on.
457
458             Termination  of  a process executing a dirty NIF can only be com‐
459             pleted up to a certain point while it executes the dirty NIF. All
460             Erlang resources, such as its registered name and its ETS tables,
461             are released. All links and monitors are triggered. The execution
462             of  the NIF is, however, not stopped. The NIF can safely continue
463             execution, allocate heap memory, and so on, but it is  of  course
464             better  to  stop executing as soon as possible. The NIF can check
465             whether  a  current   process   is   alive   using   enif_is_cur‐
466             rent_process_alive.    Communication    using    enif_send    and
467             enif_port_command is also dropped when the sending process is not
468             alive.  Deallocation  of  certain  internal  resources,  such  as
469             process heap and process control  block,  is  delayed  until  the
470             dirty NIF has completed.
471

INITIALIZATION

473         ERL_NIF_INIT(MODULE,   ErlNifFunc   funcs[],   load,  NULL,  upgrade,
474         unload):
475           This is the magic macro to initialize a NIF library. It  is  to  be
476           evaluated in global file scope.
477
478           MODULE  is  the  name of the Erlang module as an identifier without
479           string quotations. It is stringified by the macro.
480
481           funcs is a static array of function descriptors for all the  imple‐
482           mented NIFs in this library.
483
484           load,  upgrade and unload are pointers to functions. One of load or
485           upgrade is called to initialize the library. unload  is  called  to
486           release the library. All are described individually below.
487
488           The  fourth  argument  NULL is ignored. It was earlier used for the
489           deprectated reload callback which is no longer supported since  OTP
490           20.
491
492           If  compiling  a  NIF for static inclusion through --enable-static-
493           nifs, you must define  STATIC_ERLANG_NIF  before  the  ERL_NIF_INIT
494           declaration.
495
496         int    (*load)(ErlNifEnv*   env,   void**   priv_data,   ERL_NIF_TERM
497         load_info):
498           load is called when the NIF library is  loaded  and  no  previously
499           loaded library exists for this module.
500
501           *priv_data  can be set to point to some private data if the library
502           needs to keep a state between  NIF  calls.  enif_priv_data  returns
503           this  pointer.  *priv_data  is  initialized  to  NULL  when load is
504           called.
505
506           load_info is the second argument to erlang:load_nif/2.
507
508           The library fails to load if load returns anything  other  than  0.
509           load can be NULL if initialization is not needed.
510
511         int    (*upgrade)(ErlNifEnv*    env,    void**    priv_data,   void**
512         old_priv_data, ERL_NIF_TERM load_info):
513           upgrade is called when the NIF library is loaded and there  is  old
514           code of this module with a loaded NIF library.
515
516           Works  as  load,  except  that  *old_priv_data already contains the
517           value set by the last call to load or upgrade for  the  old  module
518           code.  *priv_data is initialized to NULL when upgrade is called. It
519           is allowed to write to both *priv_data and *old_priv_data.
520
521           The library fails to load if upgrade returns anything other than  0
522           or if upgrade is NULL.
523
524         void (*unload)(ErlNifEnv* env, void* priv_data):
525           unload  is called when the module code that the NIF library belongs
526           to is purged as old. New code of the same module  may  or  may  not
527           exist.
528

DATA TYPES

530         ERL_NIF_TERM:
531           Variables  of  type ERL_NIF_TERM can refer to any Erlang term. This
532           is an opaque type and values of it can only by used either as argu‐
533           ments  to  API  functions  or  as  return  values  from  NIFs.  All
534           ERL_NIF_TERMs belong to an environment (ErlNifEnv). A  term  cannot
535           be  destructed  individually,  it is valid until its environment is
536           destructed.
537
538         ErlNifEnv:
539           ErlNifEnv represents an environment that can host Erlang terms. All
540           terms  in  an  environment  are valid as long as the environment is
541           valid. ErlNifEnv is an opaque type; pointers  to  it  can  only  be
542           passed on to API functions. Two types of environments exist:
543
544           Process-bound environment:
545             Passed  as the first argument to all NIFs. All function arguments
546             passed to a NIF belong to that environment. The return value from
547             a NIF must also be a term belonging to the same environment.
548
549             A  process-bound environment contains transient information about
550             the calling Erlang process. The environment is only valid in  the
551             thread  where  it was supplied as argument until the NIF returns.
552             It is thus useless and dangerous to store  pointers  to  process-
553             bound environments between NIF calls.
554
555           Process-independent environment:
556             Created  by  calling enif_alloc_env. This environment can be used
557             to  store  terms  between  NIF  calls  and  to  send  terms  with
558             enif_send.  A  process-independent environment with all its terms
559             is valid until you explicitly invalidate it with enif_free_env or
560             enif_send.
561
562           All  contained  terms  of  a list/tuple/map must belong to the same
563           environment as the  list/tuple/map  itself.  Terms  can  be  copied
564           between environments with enif_make_copy.
565
566         ErlNifFunc:
567
568
569         typedef struct {
570             const char* name;
571             unsigned arity;
572             ERL_NIF_TERM (*fptr)(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]);
573             unsigned flags;
574         } ErlNifFunc;
575
576           Describes a NIF by its name, arity, and implementation.
577
578           fptr:
579             A pointer to the function that implements the NIF.
580
581           argv:
582             Contains the function arguments passed to the NIF.
583
584           argc:
585             The  array  length,  that  is, the function arity. argv[N-1] thus
586             denotes the Nth argument to the NIF.  Notice  that  the  argument
587             argc  allows  for the same C function to implement several Erlang
588             functions with different arity (but probably with the same name).
589
590           flags:
591             Is 0 for a regular NIF (and so its value can be omitted for stat‐
592             ically initialized ErlNifFunc instances).
593
594             flags can be used to indicate that the NIF is a dirty NIF that is
595             to be executed on a dirty scheduler thread.
596
597             If the dirty NIF is expected to be CPU-bound, its flags field  is
598             to      be      set     to     ERL_NIF_DIRTY_JOB_CPU_BOUND     or
599             ERL_NIF_DIRTY_JOB_IO_BOUND.
600
601       Note:
602           If one of the ERL_NIF_DIRTY_JOB_*_BOUND flags is set, and the  run‐
603           time system has no support for dirty schedulers, the runtime system
604           refuses to load the NIF library.
605
606
607         ErlNifBinary:
608
609
610         typedef struct {
611             unsigned size;
612             unsigned char* data;
613         } ErlNifBinary;
614
615           ErlNifBinary contains  transient  information  about  an  inspected
616           binary  term.  data is a pointer to a buffer of size bytes with the
617           raw content of the binary.
618
619           Notice that ErlNifBinary is a semi-opaque type  and  you  are  only
620           allowed to read fields size and data.
621
622         ErlNifBinaryToTerm:
623           An   enumeration   of   the   options  that  can  be  specified  to
624           enif_binary_to_term. For default behavior, use value 0.
625
626           When  receiving   data   from   untrusted   sources,   use   option
627           ERL_NIF_BIN2TERM_SAFE.
628
629         ErlNifMonitor:
630           This is an opaque data type that identifies a monitor.
631
632           The  nif  writer  is  to provide the memory for storing the monitor
633           when calling enif_monitor_process. The address of the data  is  not
634           stored  by  the runtime system, so ErlNifMonitor can be used as any
635           other data, it can be copied, moved in memory,  forgotten,  and  so
636           on. To compare two monitors, enif_compare_monitors must be used.
637
638         ErlNifPid:
639           A  process identifier (pid). In contrast to pid terms (instances of
640           ERL_NIF_TERM), ErlNifPids are self-contained and not bound  to  any
641           environment. ErlNifPid is an opaque type.
642
643         ErlNifPort:
644           A  port  identifier.  In  contrast  to  port ID terms (instances of
645           ERL_NIF_TERM), ErlNifPorts are self-contained and not bound to  any
646           environment. ErlNifPort is an opaque type.
647
648         ErlNifResourceType:
649           Each  instance  of ErlNifResourceType represents a class of memory-
650           managed resource  objects  that  can  be  garbage  collected.  Each
651           resource  type  has a unique name and a destructor function that is
652           called when objects of its type are released.
653
654         ErlNifResourceTypeInit:
655
656
657         typedef struct {
658             ErlNifResourceDtor* dtor;
659             ErlNifResourceStop* stop;
660             ErlNifResourceDown* down;
661         } ErlNifResourceTypeInit;
662
663           Initialization structure read by  enif_open_resource_type_x.
664
665         ErlNifResourceDtor:
666
667
668         typedef void ErlNifResourceDtor(ErlNifEnv* env, void* obj);
669
670           The function prototype of a resource destructor function.
671
672           The obj argument is a pointer to the resource. The only allowed use
673           for  the  resource in the destructor is to access its user data one
674           final time. The destructor is guaranteed to be  the  last  callback
675           before the resource is deallocated.
676
677         ErlNifResourceDown:
678
679
680         typedef void ErlNifResourceDown(ErlNifEnv* env, void* obj, const ErlNifPid* pid, const ErlNifMonitor* mon);
681
682           The  function  prototype of a resource down function, called on the
683           behalf of  enif_monitor_process. obj is the resource,  pid  is  the
684           identity  of  the monitored process that is exiting, and mon is the
685           identity of the monitor.
686
687         ErlNifResourceStop:
688
689
690         typedef void ErlNifResourceStop(ErlNifEnv* env, void* obj, ErlNifEvent event, int is_direct_call);
691
692           The function prototype of a resource stop function, called  on  the
693           behalf  of   enif_select.  obj  is the resource, event is OS event,
694           is_direct_call  is  true  if  the  call  is  made   directly   from
695           enif_select  or  false  if it is a scheduled call (potentially from
696           another thread).
697
698         ErlNifCharEncoding:
699
700
701         typedef enum {
702             ERL_NIF_LATIN1
703         }ErlNifCharEncoding;
704
705           The character encoding used in strings and  atoms.  The  only  sup‐
706           ported encoding is ERL_NIF_LATIN1 for ISO Latin-1 (8-bit ASCII).
707
708         ErlNifSysInfo:
709           Used  by  enif_system_info  to return information about the runtime
710           system. Contains the same content as ErlDrvSysInfo.
711
712         ErlNifSInt64:
713           A native signed 64-bit integer type.
714
715         ErlNifUInt64:
716           A native unsigned 64-bit integer type.
717
718         ErlNifTime:
719           A signed 64-bit integer type for representation of time.
720
721         ErlNifTimeUnit:
722           An enumeration of time units supported by the NIF API:
723
724           ERL_NIF_SEC:
725             Seconds
726
727           ERL_NIF_MSEC:
728             Milliseconds
729
730           ERL_NIF_USEC:
731             Microseconds
732
733           ERL_NIF_NSEC:
734             Nanoseconds
735
736         ErlNifUniqueInteger:
737           An enumeration  of  the  properties  that  can  be  requested  from
738           enif_unique_integer. For default properties, use value 0.
739
740           ERL_NIF_UNIQUE_POSITIVE:
741             Return only positive integers.
742
743           ERL_NIF_UNIQUE_MONOTONIC:
744             Return  only   strictly  monotonically  increasing integer corre‐
745             sponding to creation time.
746
747         ErlNifHash:
748           An enumeration of the supported hash types that  can  be  generated
749           using enif_hash.
750
751           ERL_NIF_INTERNAL_HASH:
752             Non-portable hash function that only guarantees the same hash for
753             the same term within one Erlang VM instance.
754
755             It  takes  32-bit  salt  values  and  generates   hashes   within
756             0..2^32-1.
757
758           ERL_NIF_PHASH2:
759             Portable  hash  function  that  gives  the same hash for the same
760             Erlang term regardless of machine architecture and ERTS version.
761
762             It ignores salt values and generates hashes within 0..2^27-1.
763
764             Slower   than   ERL_NIF_INTERNAL_HASH.    It    corresponds    to
765             erlang:phash2/1.
766
767         SysIOVec:
768           A  system  I/O  vector,  as  used  by writev on Unix and WSASend on
769           Win32. It is used in ErlNifIOVec and by enif_ioq_peek.
770
771         ErlNifIOVec:
772
773
774         typedef struct {
775           int iovcnt;
776           size_t size;
777           SysIOVec* iov;
778         } ErlNifIOVec;
779
780           An I/O vector containing iovcnt SysIOVecs pointing to the data.  It
781           is used by enif_inspect_iovec and enif_ioq_enqv.
782
783         ErlNifIOQueueOpts:
784            Options to configure a ErlNifIOQueue.
785
786           ERL_NIF_IOQ_NORMAL:
787             Create a normal I/O Queue
788

EXPORTS

790       void *enif_alloc(size_t size)
791
792              Allocates memory of size bytes.
793
794              Returns NULL if the allocation fails.
795
796              The  returned  pointer is suitably aligned for any built-in type
797              that fit in the allocated memory.
798
799       int enif_alloc_binary(size_t size, ErlNifBinary* bin)
800
801              Allocates a new binary  of  size  size  bytes.  Initializes  the
802              structure  pointed  to  by bin to refer to the allocated binary.
803              The binary must either be  released  by  enif_release_binary  or
804              ownership  transferred  to an Erlang term with enif_make_binary.
805              An allocated (and owned) ErlNifBinary can be  kept  between  NIF
806              calls.
807
808              Returns true on success, or false if allocation fails.
809
810       ErlNifEnv *enif_alloc_env()
811
812              Allocates a new process-independent environment. The environment
813              can be used to hold terms that are not  bound  to  any  process.
814              Such  terms  can  later  be copied to a process environment with
815              enif_make_copy or be  sent  to  a  process  as  a  message  with
816              enif_send.
817
818              Returns pointer to the new environment.
819
820       void *enif_alloc_resource(ErlNifResourceType*
821               type, unsigned size)
822
823              Allocates a memory-managed resource object of type type and size
824              size bytes.
825
826       size_t enif_binary_to_term(ErlNifEnv *env,
827               const unsigned char* data, size_t size, ERL_NIF_TERM *term,
828               ErlNifBinaryToTerm opts)
829
830              Creates a term that is the result of decoding the binary data at
831              data,  which  must  be  encoded according to the Erlang external
832              term format. No more than size bytes are read from  data.  Argu‐
833              ment    opts    corresponds    to   the   second   argument   to
834              erlang:binary_to_term/2   and    must    be    either    0    or
835              ERL_NIF_BIN2TERM_SAFE.
836
837              On  success,  stores the resulting term at *term and returns the
838              number of bytes read. Returns 0 if decoding fails or if opts  is
839              invalid.
840
841              See   also   ErlNifBinaryToTerm,   erlang:binary_to_term/2,  and
842              enif_term_to_binary.
843
844       void enif_clear_env(ErlNifEnv* env)
845
846              Frees all terms in an environment and clears it for  reuse.  The
847              environment must have been allocated with enif_alloc_env.
848
849       int enif_compare(ERL_NIF_TERM lhs, ERL_NIF_TERM rhs)
850
851              Returns  an integer < 0 if lhs < rhs, 0 if lhs = rhs, and > 0 if
852              lhs > rhs. Corresponds to the Erlang operators ==,  /=,  =<,  <,
853              >=, and > (but not =:= or =/=).
854
855       int enif_compare_monitors(const ErlNifMonitor
856               *monitor1, const ErlNifMonitor *monitor2)
857
858              Compares  two  ErlNifMonitors.  Can  also  be used to imply some
859              artificial order on monitors, for whatever reason.
860
861              Returns 0 if monitor1 and monitor2 are equal, < 0 if monitor1  <
862              monitor2, and > 0 if monitor1 > monitor2.
863
864       void enif_cond_broadcast(ErlNifCond *cnd)
865
866              Same as erl_drv_cond_broadcast.
867
868       ErlNifCond *enif_cond_create(char *name)
869
870              Same as erl_drv_cond_create.
871
872       void enif_cond_destroy(ErlNifCond *cnd)
873
874              Same as erl_drv_cond_destroy.
875
876       void enif_cond_signal(ErlNifCond *cnd)
877
878              Same as erl_drv_cond_signal.
879
880       void enif_cond_wait(ErlNifCond *cnd, ErlNifMutex *mtx)
881
882              Same as erl_drv_cond_wait.
883
884       int enif_consume_timeslice(ErlNifEnv *env, int percent)
885
886              Gives the runtime system a hint about how much CPU time the cur‐
887              rent NIF call has consumed since the last  hint,  or  since  the
888              start  of  the  NIF  if no previous hint has been specified. The
889              time is specified as a percent of the timeslice that  a  process
890              is  allowed  to execute Erlang code until it can be suspended to
891              give time for other runnable processes. The scheduling timeslice
892              is not an exact entity, but can usually be approximated to about
893              1 millisecond.
894
895              Notice that it is up to the runtime system to determine  if  and
896              how  to  use this information. Implementations on some platforms
897              can use other means to determine consumed CPU time. Lengthy NIFs
898              should regardless of this frequently call enif_consume_timeslice
899              to determine if it is allowed to continue execution.
900
901              Argument percent must be an integer  between  1  and  100.  This
902              function  must  only  be  called  from a NIF-calling thread, and
903              argument env must be the environment of the calling process.
904
905              Returns 1 if the timeslice is exhausted, otherwise 0.  If  1  is
906              returned,  the NIF is to return as soon as possible in order for
907              the process to yield.
908
909              This function is provided to better support co-operative  sched‐
910              uling, improve system responsiveness, and make it easier to pre‐
911              vent misbehaviors of the VM because  of  a  NIF  monopolizing  a
912              scheduler  thread.  It can be used to divide  length work into a
913              number of repeated NIF calls without the need to create threads.
914
915              See also the warning text at the beginning of this manual page.
916
917       ErlNifTime enif_convert_time_unit(ErlNifTime
918               val, ErlNifTimeUnit from, ErlNifTimeUnit to)
919
920              Converts the val value of time unit from  to  the  corresponding
921              value  of  time  unit  to. The result is rounded using the floor
922              function.
923
924                val:
925                  Value to convert time unit for.
926
927                from:
928                  Time unit of val.
929
930                to:
931                  Time unit of returned value.
932
933              Returns ERL_NIF_TIME_ERROR if called with an invalid  time  unit
934              argument.
935
936              See also ErlNifTime and ErlNifTimeUnit.
937
938       ERL_NIF_TERM enif_cpu_time(ErlNifEnv *)
939
940              Returns  the  CPU time in the same format as erlang:timestamp().
941              The CPU time is the time the current logical CPU has spent  exe‐
942              cuting  since  some  arbitrary point in the past. If the OS does
943              not  support  fetching   this   value,   enif_cpu_time   invokes
944              enif_make_badarg.
945
946       int enif_demonitor_process(ErlNifEnv* env, void* obj,
947             const ErlNifMonitor* mon)
948
949              Cancels  a  monitor  created  earlier with enif_monitor_process.
950              Argument obj is a pointer to the resource  holding  the  monitor
951              and *mon identifies the monitor.
952
953              Returns  0  if  the  monitor  was  successfully  identified  and
954              removed. Returns a non-zero value if the monitor  could  not  be
955              identified, which means it was either
956
957                * never created for this resource
958
959                * already cancelled
960
961                * already triggered
962
963                * just about to be triggered by a concurrent thread
964
965              This  function  is  only  thread-safe when the emulator with SMP
966              support is used. It can only be used in a non-SMP emulator  from
967              a NIF-calling thread.
968
969       int enif_equal_tids(ErlNifTid tid1, ErlNifTid tid2)
970
971              Same as erl_drv_equal_tids.
972
973       void enif_free(void* ptr)
974
975              Frees memory allocated by enif_alloc.
976
977       void enif_free_env(ErlNifEnv* env)
978
979              Frees  an  environment  allocated with enif_alloc_env. All terms
980              created in the environment are freed as well.
981
982       void enif_free_iovec(ErlNifIOvec* iov)
983
984              Frees an io vector returned  from  enif_inspect_iovec.  This  is
985              needed    only    if   a   NULL   environment   is   passed   to
986              enif_inspect_iovec.
987
988              ErlNifIOVec *iovec = NULL;
989              size_t max_elements = 128;
990              ERL_NIF_TERM tail;
991              if (!enif_inspect_iovec(NULL, max_elements, term, &tail, iovec))
992                return 0;
993
994              // Do things with the iovec
995
996              /* Free the iovector, possibly in another thread or nif function call */
997              enif_free_iovec(iovec);
998
999       int enif_get_atom(ErlNifEnv* env, ERL_NIF_TERM
1000               term, char* buf, unsigned size, ErlNifCharEncoding encode)
1001
1002              Writes a NULL-terminated string in the buffer pointed to by  buf
1003              of  size  size,  consisting  of the string representation of the
1004              atom term with encoding encode.
1005
1006              Returns the number of bytes written (including terminating  NULL
1007              character)  or  0  if term is not an atom with maximum length of
1008              size-1.
1009
1010       int enif_get_atom_length(ErlNifEnv* env,
1011               ERL_NIF_TERM term, unsigned* len, ErlNifCharEncoding encode)
1012
1013              Sets *len to the length (number of bytes  excluding  terminating
1014              NULL character) of the atom term with encoding encode.
1015
1016              Returns true on success, or false if term is not an atom.
1017
1018       int enif_get_double(ErlNifEnv* env,
1019               ERL_NIF_TERM term, double* dp)
1020
1021              Sets *dp to the floating-point value of term.
1022
1023              Returns true on success, or false if term is not a float.
1024
1025       int enif_get_int(ErlNifEnv* env, ERL_NIF_TERM
1026               term, int* ip)
1027
1028              Sets *ip to the integer value of term.
1029
1030              Returns  true  on success, or false if term is not an integer or
1031              is outside the bounds of type int.
1032
1033       int enif_get_int64(ErlNifEnv* env, ERL_NIF_TERM
1034               term, ErlNifSInt64* ip)
1035
1036              Sets *ip to the integer value of term.
1037
1038              Returns true on success, or false if term is not an  integer  or
1039              is outside the bounds of a signed 64-bit integer.
1040
1041       int enif_get_local_pid(ErlNifEnv* env,
1042               ERL_NIF_TERM term, ErlNifPid* pid)
1043
1044              If  term  is the pid of a node local process, this function ini‐
1045              tializes the pid variable *pid from it and returns true.  Other‐
1046              wise  returns  false.  No check is done to see if the process is
1047              alive.
1048
1049       int enif_get_local_port(ErlNifEnv* env,
1050               ERL_NIF_TERM term, ErlNifPort* port_id)
1051
1052              If term identifies a node local port, this function  initializes
1053              the  port  variable *port_id from it and returns true. Otherwise
1054              returns false. No check is done to see if the port is alive.
1055
1056       int enif_get_list_cell(ErlNifEnv* env,
1057               ERL_NIF_TERM list, ERL_NIF_TERM* head, ERL_NIF_TERM* tail)
1058
1059              Sets *head and *tail from list list.
1060
1061              Returns true on success, or false if it is not  a  list  or  the
1062              list is empty.
1063
1064       int enif_get_list_length(ErlNifEnv* env,
1065               ERL_NIF_TERM term, unsigned* len)
1066
1067              Sets *len to the length of list term.
1068
1069              Returns true on success, or false if term is not a proper list.
1070
1071       int enif_get_long(ErlNifEnv* env, ERL_NIF_TERM
1072               term, long int* ip)
1073
1074              Sets *ip to the long integer value of term.
1075
1076              Returns  true  on success, or false if term is not an integer or
1077              is outside the bounds of type long int.
1078
1079       int enif_get_map_size(ErlNifEnv* env,
1080               ERL_NIF_TERM term, size_t *size)
1081
1082              Sets *size to the number of key-value pairs in the map term.
1083
1084              Returns true on success, or false if term is not a map.
1085
1086       int enif_get_map_value(ErlNifEnv* env,
1087               ERL_NIF_TERM map, ERL_NIF_TERM key, ERL_NIF_TERM* value)
1088
1089              Sets *value to the value associated with key in the map map.
1090
1091              Returns true on success, or false if map is not a map or if  map
1092              does not contain key.
1093
1094       int enif_get_resource(ErlNifEnv* env,
1095               ERL_NIF_TERM term, ErlNifResourceType* type, void** objp)
1096
1097              Sets *objp to point to the resource object referred to by term.
1098
1099              Returns  true  on success, or false if term is not a handle to a
1100              resource object of type type.
1101
1102       int enif_get_string(ErlNifEnv* env,
1103               ERL_NIF_TERM list, char* buf, unsigned size,
1104               ErlNifCharEncoding encode)
1105
1106              Writes a NULL-terminated string in the buffer pointed to by  buf
1107              with size size, consisting of the characters in the string list.
1108              The characters are written using encoding encode.
1109
1110              Returns one of the following:
1111
1112                * The number of  bytes  written  (including  terminating  NULL
1113                  character)
1114
1115                * -size if the string was truncated because of buffer space
1116
1117                * 0 if list is not a string that can be encoded with encode or
1118                  if size was < 1.
1119
1120              The written string is always NULL-terminated, unless buffer size
1121              is < 1.
1122
1123       int enif_get_tuple(ErlNifEnv* env, ERL_NIF_TERM
1124               term, int* arity, const ERL_NIF_TERM** array)
1125
1126              If  term  is  a  tuple, this function sets *array to point to an
1127              array containing the elements of the tuple, and sets  *arity  to
1128              the  number  of elements. Notice that the array is read-only and
1129              (*array)[N-1] is the Nth element of the tuple. *array  is  unde‐
1130              fined if the arity of the tuple is zero.
1131
1132              Returns true on success, or false if term is not a tuple.
1133
1134       int enif_get_uint(ErlNifEnv* env, ERL_NIF_TERM
1135               term, unsigned int* ip)
1136
1137              Sets *ip to the unsigned integer value of term.
1138
1139              Returns  true  on  success,  or false if term is not an unsigned
1140              integer or is outside the bounds of type unsigned int.
1141
1142       int enif_get_uint64(ErlNifEnv* env,
1143               ERL_NIF_TERM term, ErlNifUInt64* ip)
1144
1145              Sets *ip to the unsigned integer value of term.
1146
1147              Returns true on success, or false if term  is  not  an  unsigned
1148              integer or is outside the bounds of an unsigned 64-bit integer.
1149
1150       int enif_get_ulong(ErlNifEnv* env, ERL_NIF_TERM
1151               term, unsigned long* ip)
1152
1153              Sets *ip to the unsigned long integer value of term.
1154
1155              Returns  true  on  success,  or false if term is not an unsigned
1156              integer or is outside the bounds of type unsigned long.
1157
1158       int enif_getenv(const char* key, char* value,
1159               size_t *value_size)
1160
1161              Same as erl_drv_getenv.
1162
1163       int enif_has_pending_exception(ErlNifEnv* env,
1164               ERL_NIF_TERM* reason)
1165
1166              Returns true if a pending exception is associated with the envi‐
1167              ronment  env. If reason is a NULL pointer, ignore it. Otherwise,
1168              if a pending exception associated with env exists,  set  *reason
1169              to   the   value   of   the  exception  term.  For  example,  if
1170              enif_make_badarg is called to set a pending badarg exception,  a
1171              later  call  to  enif_has_pending_exception(env,  &reason)  sets
1172              *reason to the atom badarg, then return true.
1173
1174              See also enif_make_badarg and enif_raise_exception.
1175
1176       ErlNifUInt64 enif_hash(ErlNifHash type, ERL_NIF_TERM term, ErlNifUInt64
1177       salt)
1178
1179              Hashes term according to the specified ErlNifHash type.
1180
1181              Ranges  of  taken salt (if any) and returned value depend on the
1182              hash type.
1183
1184       int enif_inspect_binary(ErlNifEnv* env,
1185               ERL_NIF_TERM bin_term, ErlNifBinary* bin)
1186
1187              Initializes the structure pointed to  by  bin  with  information
1188              about binary term bin_term.
1189
1190              Returns true on success, or false if bin_term is not a binary.
1191
1192       int enif_inspect_iolist_as_binary(ErlNifEnv*
1193               env, ERL_NIF_TERM term, ErlNifBinary* bin)
1194
1195              Initializes  the  structure  pointed to by bin with a continuous
1196              buffer  with  the  same  byte  content  as   iolist.   As   with
1197              inspect_binary, the data pointed to by bin is transient and does
1198              not need to be released.
1199
1200              Returns true on success, or false if iolist is not an iolist.
1201
1202       int enif_inspect_iovec(ErlNifEnv*
1203               env,    size_t    max_elements,    ERL_NIF_TERM     iovec_term,
1204       ERL_NIF_TERM* tail,
1205               ErlNifIOVec** iovec)
1206
1207              Fills  iovec  with  the list of binaries provided in iovec_term.
1208              The number of  elements  handled  in  the  call  is  limited  to
1209              max_elements, and tail is set to the remainder of the list. Note
1210              that the output may be longer than max_elements  on  some  plat‐
1211              forms.
1212
1213              To  create  a  list  of  binaries  from an arbitrary iolist, use
1214              erlang:iolist_to_iovec/1.
1215
1216              When calling this function, iovec should contain  a  pointer  to
1217              NULL or a ErlNifIOVec structure that should be used if possible.
1218              e.g.
1219
1220              /* Don't use a pre-allocated structure */
1221              ErlNifIOVec *iovec = NULL;
1222              enif_inspect_iovec(env, max_elements, term, &tail, &iovec);
1223
1224              /* Use a stack-allocated vector as an optimization for vectors with few elements */
1225              ErlNifIOVec vec, *iovec = &vec;
1226              enif_inspect_iovec(env, max_elements, term, &tail, &iovec);
1227
1228
1229              The contents of the iovec is valid until the called nif function
1230              returns.  If  the  iovec  should  be  valid  after  the nif call
1231              returns, it is possible to call this function with a NULL  envi‐
1232              ronment.  If  no environment is given the iovec owns the data in
1233              the  vector  and  it  has   to   be   explicitly   freed   using
1234              enif_free_iovec.
1235
1236              Returns true on success, or false if iovec_term not an iovec.
1237
1238       ErlNifIOQueue *enif_ioq_create(ErlNifIOQueueOpts opts)
1239
1240              Create  a new I/O Queue that can be used to store data. opts has
1241              to be set to ERL_NIF_IOQ_NORMAL.
1242
1243       void enif_ioq_destroy(ErlNifIOQueue *q)
1244
1245              Destroy the I/O queue and free all of it's contents
1246
1247       int enif_ioq_deq(ErlNifIOQueue *q, size_t count, size_t *size)
1248
1249              Dequeue count bytes from the I/O queue. If size is not NULL, the
1250              new size of the queue is placed there.
1251
1252              Returns  true  on  success, or false if the I/O does not contain
1253              count bytes. On failure the queue is left un-altered.
1254
1255       int enif_ioq_enq_binary(ErlNifIOQueue  *q,  ErlNifBinary  *bin,  size_t
1256       skip)
1257
1258              Enqueue the bin into q skipping the first skip bytes.
1259
1260              Returns  true  on  success, or false if skip is greater than the
1261              size of bin. Any ownership of the binary data is transferred  to
1262              the  queue and bin is to be considered read-only for the rest of
1263              the NIF call and then as released.
1264
1265       int enif_ioq_enqv(ErlNifIOQueue *q, ErlNifIOVec *iovec, size_t skip)
1266
1267              Enqueue the iovec into q skipping the first skip bytes.
1268
1269              Returns true on success, or false if skip is  greater  than  the
1270              size of iovec.
1271
1272       SysIOVec *enif_ioq_peek(ErlNifIOQueue *q, int *iovlen)
1273
1274              Get the I/O queue as a pointer to an array of SysIOVecs. It also
1275              returns the number of elements in iovlen. This is the  only  way
1276              to get data out of the queue.
1277
1278              Nothing is removed from the queue by this function, that must be
1279              done with enif_ioq_deq.
1280
1281              The returned array is suitable to use with the Unix system  call
1282              writev.
1283
1284       size_t enif_ioq_size(ErlNifIOQueue *q)
1285
1286              Get the size of q.
1287
1288       int enif_is_atom(ErlNifEnv* env, ERL_NIF_TERM term)
1289
1290              Returns true if term is an atom.
1291
1292       int enif_is_binary(ErlNifEnv* env, ERL_NIF_TERM term)
1293
1294              Returns true if term is a binary.
1295
1296       int enif_is_current_process_alive(ErlNifEnv* env)
1297
1298              Returns  true  if  the  currently executing process is currently
1299              alive, otherwise false.
1300
1301              This function can only be used from a  NIF-calling  thread,  and
1302              with  an  environment  corresponding to currently executing pro‐
1303              cesses.
1304
1305       int enif_is_empty_list(ErlNifEnv* env,
1306               ERL_NIF_TERM term)
1307
1308              Returns true if term is an empty list.
1309
1310       int enif_is_exception(ErlNifEnv* env,
1311               ERL_NIF_TERM term)
1312
1313              Return true if term is an exception.
1314
1315       int enif_is_fun(ErlNifEnv* env, ERL_NIF_TERM
1316               term)
1317
1318              Returns true if term is a fun.
1319
1320       int enif_is_identical(ERL_NIF_TERM lhs,
1321               ERL_NIF_TERM rhs)
1322
1323              Returns true if the two terms are identical. Corresponds to  the
1324              Erlang operators =:= and =/=.
1325
1326       int enif_is_list(ErlNifEnv* env, ERL_NIF_TERM term)
1327
1328              Returns true if term is a list.
1329
1330       int enif_is_map(ErlNifEnv* env, ERL_NIF_TERM
1331               term)
1332
1333              Returns true if term is a map, otherwise false.
1334
1335       int enif_is_number(ErlNifEnv* env, ERL_NIF_TERM
1336               term)
1337
1338              Returns true if term is a number.
1339
1340       int enif_is_pid(ErlNifEnv* env, ERL_NIF_TERM term)
1341
1342              Returns true if term is a pid.
1343
1344       int enif_is_port(ErlNifEnv* env, ERL_NIF_TERM term)
1345
1346              Returns true if term is a port.
1347
1348       int enif_is_port_alive(ErlNifEnv* env,
1349               ErlNifPort *port_id)
1350
1351              Returns true if port_id is alive.
1352
1353              This  function  is  only  thread-safe when the emulator with SMP
1354              support is used. It can only be used in a non-SMP emulator  from
1355              a NIF-calling thread.
1356
1357       int enif_is_process_alive(ErlNifEnv* env,
1358               ErlNifPid *pid)
1359
1360              Returns true if pid is alive.
1361
1362              This  function  is  only  thread-safe when the emulator with SMP
1363              support is used. It can only be used in a non-SMP emulator  from
1364              a NIF-calling thread.
1365
1366       int enif_is_ref(ErlNifEnv* env, ERL_NIF_TERM term)
1367
1368              Returns true if term is a reference.
1369
1370       int enif_is_tuple(ErlNifEnv* env, ERL_NIF_TERM term)
1371
1372              Returns true if term is a tuple.
1373
1374       int enif_keep_resource(void* obj)
1375
1376              Adds   a   reference   to  resource  object  obj  obtained  from
1377              enif_alloc_resource. Each  call  to  enif_keep_resource  for  an
1378              object  must  be  balanced  by  a  call to enif_release_resource
1379              before the object is destructed.
1380
1381       ERL_NIF_TERM enif_make_atom(ErlNifEnv* env, const char* name)
1382
1383              Creates an atom term from the NULL-terminated C-string name with
1384              ISO  Latin-1 encoding. If the length of name exceeds the maximum
1385              length allowed for  an  atom  (255  characters),  enif_make_atom
1386              invokes enif_make_badarg.
1387
1388       ERL_NIF_TERM enif_make_atom_len(ErlNifEnv* env,
1389               const char* name, size_t len)
1390
1391              Create  an  atom term from the string name with length len. NULL
1392              characters are treated as any other characters. If  len  exceeds
1393              the  maximum  length  allowed  for  an  atom  (255  characters),
1394              enif_make_atom invokes enif_make_badarg.
1395
1396       ERL_NIF_TERM enif_make_badarg(ErlNifEnv* env)
1397
1398              Makes a badarg exception to be returned from a  NIF,  and  asso‐
1399              ciates  it  with  environment env. Once a NIF or any function it
1400              calls invokes  enif_make_badarg,  the  runtime  ensures  that  a
1401              badarg exception is raised when the NIF returns, even if the NIF
1402              attempts to return a non-exception term instead.
1403
1404              The return value from enif_make_badarg can be used only  as  the
1405              return  value  from  the  NIF that invoked it (directly or indi‐
1406              rectly) or be passed to enif_is_exception, but not to any  other
1407              NIF API function.
1408
1409              See also enif_has_pending_exception and enif_raise_exception.
1410
1411          Note:
1412              Before   ERTS   7.0  (Erlang/OTP  18),  the  return  value  from
1413              enif_make_badarg had to be returned from the NIF. This  require‐
1414              ment  is  now lifted as the return value from the NIF is ignored
1415              if enif_make_badarg has been invoked.
1416
1417
1418       ERL_NIF_TERM enif_make_binary(ErlNifEnv* env, ErlNifBinary* bin)
1419
1420              Makes a binary term from bin. Any ownership of the  binary  data
1421              is  transferred  to the created term and bin is to be considered
1422              read-only for the rest of the NIF call and then as released.
1423
1424       ERL_NIF_TERM enif_make_copy(ErlNifEnv* dst_env,
1425               ERL_NIF_TERM src_term)
1426
1427              Makes a copy of term src_term. The copy is created  in  environ‐
1428              ment dst_env. The source term can be located in any environment.
1429
1430       ERL_NIF_TERM enif_make_double(ErlNifEnv* env, double d)
1431
1432              Creates  a floating-point term from a double. If argument double
1433              is   not   finite   or   is   NaN,   enif_make_double    invokes
1434              enif_make_badarg.
1435
1436       int enif_make_existing_atom(ErlNifEnv* env,
1437               const char* name, ERL_NIF_TERM* atom, ErlNifCharEncoding
1438               encode)
1439
1440              Tries  to  create  the term of an already existing atom from the
1441              NULL-terminated C-string name with encoding encode.
1442
1443              If the atom already exists, this function  stores  the  term  in
1444              *atom  and  returns true, otherwise false. Also returns false if
1445              the length of name exceeds the maximum  length  allowed  for  an
1446              atom (255 characters).
1447
1448       int enif_make_existing_atom_len(ErlNifEnv* env,
1449               const char* name, size_t len, ERL_NIF_TERM* atom, ErlNifCharEn‐
1450       coding
1451               encoding)
1452
1453              Tries to create the term of an already existing  atom  from  the
1454              string name with length len and encoding encode. NULL characters
1455              are treated as any other characters.
1456
1457              If the atom already exists, this function  stores  the  term  in
1458              *atom  and  returns true, otherwise false. Also returns false if
1459              len exceeds the maximum length allowed for an atom (255  charac‐
1460              ters).
1461
1462       ERL_NIF_TERM enif_make_int(ErlNifEnv* env, int i)
1463
1464              Creates an integer term.
1465
1466       ERL_NIF_TERM enif_make_int64(ErlNifEnv* env, ErlNifSInt64 i)
1467
1468              Creates an integer term from a signed 64-bit integer.
1469
1470       ERL_NIF_TERM enif_make_list(ErlNifEnv* env, unsigned cnt, ...)
1471
1472              Creates  an ordinary list term of length cnt. Expects cnt number
1473              of arguments (after cnt) of type ERL_NIF_TERM as the elements of
1474              the list.
1475
1476              Returns an empty list if cnt is 0.
1477
1478       ERL_NIF_TERM enif_make_list1(ErlNifEnv* env, ERL_NIF_TERM e1)
1479       ERL_NIF_TERM enif_make_list2(ErlNifEnv* env,
1480               ERL_NIF_TERM e1, ERL_NIF_TERM e2)
1481       ERL_NIF_TERM enif_make_list3(ErlNifEnv* env,
1482               ERL_NIF_TERM e1, ERL_NIF_TERM e2, ERL_NIF_TERM e3)
1483       ERL_NIF_TERM enif_make_list4(ErlNifEnv* env,
1484               ERL_NIF_TERM e1, ..., ERL_NIF_TERM e4)
1485       ERL_NIF_TERM enif_make_list5(ErlNifEnv* env,
1486               ERL_NIF_TERM e1, ..., ERL_NIF_TERM e5)
1487       ERL_NIF_TERM enif_make_list6(ErlNifEnv* env,
1488               ERL_NIF_TERM e1, ..., ERL_NIF_TERM e6)
1489       ERL_NIF_TERM enif_make_list7(ErlNifEnv* env,
1490               ERL_NIF_TERM e1, ..., ERL_NIF_TERM e7)
1491       ERL_NIF_TERM enif_make_list8(ErlNifEnv* env,
1492               ERL_NIF_TERM e1, ..., ERL_NIF_TERM e8)
1493       ERL_NIF_TERM enif_make_list9(ErlNifEnv* env,
1494               ERL_NIF_TERM e1, ..., ERL_NIF_TERM e9)
1495
1496              Creates an ordinary list term with length indicated by the func‐
1497              tion name. Prefer these functions  (macros)  over  the  variadic
1498              enif_make_list  to  get  a  compile-time  error if the number of
1499              arguments does not match.
1500
1501       ERL_NIF_TERM enif_make_list_cell(ErlNifEnv*
1502               env, ERL_NIF_TERM head, ERL_NIF_TERM tail)
1503
1504              Creates a list cell [head | tail].
1505
1506       ERL_NIF_TERM    enif_make_list_from_array(ErlNifEnv*     env,     const
1507       ERL_NIF_TERM
1508                 arr[], unsigned cnt)
1509
1510              Creates an ordinary list containing the elements of array arr of
1511              length cnt.
1512
1513              Returns an empty list if cnt is 0.
1514
1515       ERL_NIF_TERM enif_make_long(ErlNifEnv* env, long int i)
1516
1517              Creates an integer term from a long int.
1518
1519       int enif_make_map_put(ErlNifEnv* env,
1520               ERL_NIF_TERM map_in, ERL_NIF_TERM key, ERL_NIF_TERM value,
1521               ERL_NIF_TERM* map_out)
1522
1523              Makes a copy of map map_in and inserts key with  value.  If  key
1524              already  exists  in map_in, the old associated value is replaced
1525              by value.
1526
1527              If successful, this function sets *map_out to the  new  map  and
1528              returns true. Returns false if map_in is not a map.
1529
1530              The map_in term must belong to environment env.
1531
1532       int enif_make_map_remove(ErlNifEnv* env,
1533               ERL_NIF_TERM map_in, ERL_NIF_TERM key, ERL_NIF_TERM* map_out)
1534
1535              If map map_in contains key, this function makes a copy of map_in
1536              in *map_out, and removes key and the associated  value.  If  map
1537              map_in does not contain key, *map_out is set to map_in.
1538
1539              Returns true on success, or false if map_in is not a map.
1540
1541              The map_in term must belong to environment env.
1542
1543       int enif_make_map_update(ErlNifEnv* env,
1544               ERL_NIF_TERM map_in, ERL_NIF_TERM key, ERL_NIF_TERM new_value,
1545               ERL_NIF_TERM* map_out)
1546
1547              Makes  a copy of map map_in and replace the old associated value
1548              for key with new_value.
1549
1550              If successful, this function sets *map_out to the  new  map  and
1551              returns true. Returns false if map_in is not a map or if it does
1552              not contain key.
1553
1554              The map_in term must belong to environment env.
1555
1556       unsigned char *enif_make_new_binary(ErlNifEnv*
1557               env, size_t size, ERL_NIF_TERM* termp)
1558
1559              Allocates a binary of size size  bytes  and  creates  an  owning
1560              term.  The binary data is mutable until the calling NIF returns.
1561              This is a quick way to create a new binary without having to use
1562              ErlNifBinary.  The  drawbacks are that the binary cannot be kept
1563              between NIF calls and it cannot be reallocated.
1564
1565              Returns a pointer to the raw binary data and sets *termp to  the
1566              binary term.
1567
1568       ERL_NIF_TERM enif_make_new_map(ErlNifEnv* env)
1569
1570              Makes an empty map term.
1571
1572       ERL_NIF_TERM enif_make_pid(ErlNifEnv* env, const ErlNifPid* pid)
1573
1574              Makes a pid term from *pid.
1575
1576       ERL_NIF_TERM enif_make_ref(ErlNifEnv* env)
1577
1578              Creates a reference like erlang:make_ref/0.
1579
1580       ERL_NIF_TERM enif_make_resource(ErlNifEnv* env, void* obj)
1581
1582              Creates  an  opaque  handle  to a memory-managed resource object
1583              obtained by enif_alloc_resource. No ownership transfer is  done,
1584              as   the   resource   object  still  needs  to  be  released  by
1585              enif_release_resource.  However,  notice  that   the   call   to
1586              enif_release_resource  can occur immediately after obtaining the
1587              term from enif_make_resource, in which case the resource  object
1588              is  deallocated  when  the  term  is garbage collected. For more
1589              details, see the example of creating and  returning  a  resource
1590              object in the User's Guide.
1591
1592          Note:
1593              Since  ERTS 9.0 (OTP-20.0), resource terms have a defined behav‐
1594              ior when  compared  and  serialized  through  term_to_binary  or
1595              passed between nodes.
1596
1597                * Two  resource  terms will compare equal iff they would yield
1598                  the  same   resource   object   pointer   when   passed   to
1599                  enif_get_resource.
1600
1601                * A  resoure  term  can  be serialized with term_to_binary and
1602                  later be fully recreated if the  resource  object  is  still
1603                  alive  when  binary_to_term is called. A stale resource term
1604                  will be returned from binary_to_term if the resource  object
1605                  has  been  deallocated.  enif_get_resource will return false
1606                  for stale resource terms.
1607
1608                  The same principles  of  serialization  apply  when  passing
1609                  resource terms in messages to remote nodes and back again. A
1610                  resource term will act stale on all nodes  except  the  node
1611                  where its resource object is still alive in memory.
1612
1613              Before ERTS 9.0 (OTP-20.0), all resource terms did compare equal
1614              to each other and to empty binaries (<<>>). If serialized,  they
1615              would be recreated as plain empty binaries.
1616
1617
1618       ERL_NIF_TERM enif_make_resource_binary(ErlNifEnv* env, void* obj, const
1619               void* data, size_t size)
1620
1621              Creates  a  binary  term  that  is  memory-managed by a resource
1622              object obj obtained by enif_alloc_resource. The returned  binary
1623              term  consists of size bytes pointed to by data. This raw binary
1624              data must be kept readable and unchanged until the destructor of
1625              the  resource  is called. The binary data can be stored external
1626              to the resource object, in which case the destructor is  respon‐
1627              sible for releasing the data.
1628
1629              Several binary terms can be managed by the same resource object.
1630              The destructor is not called until the last  binary  is  garbage
1631              collected.  This  can  be  useful to return different parts of a
1632              larger binary buffer.
1633
1634              As with enif_make_resource, no ownership transfer is  done.  The
1635              resource still needs to be released with enif_release_resource.
1636
1637       int enif_make_reverse_list(ErlNifEnv* env, ERL_NIF_TERM list_in,
1638               ERL_NIF_TERM *list_out)
1639
1640              Sets  *list_out  to  the  reverse  list  of the list list_in and
1641              returns true, or returns false if list_in is not a list.
1642
1643              This function is only to be used on short lists, as  a  copy  is
1644              created  of  the list, which is not released until after the NIF
1645              returns.
1646
1647              The list_in term must belong to environment env.
1648
1649       ERL_NIF_TERM enif_make_string(ErlNifEnv* env,
1650               const char* string, ErlNifCharEncoding encoding)
1651
1652              Creates a list containing the characters of the  NULL-terminated
1653              string string with encoding encoding.
1654
1655       ERL_NIF_TERM enif_make_string_len(ErlNifEnv*
1656               env, const char* string, size_t len, ErlNifCharEncoding
1657               encoding)
1658
1659              Creates  a  list  containing the characters of the string string
1660              with length len  and  encoding  encoding.  NULL  characters  are
1661              treated as any other characters.
1662
1663       ERL_NIF_TERM enif_make_sub_binary(ErlNifEnv*
1664               env, ERL_NIF_TERM bin_term, size_t pos, size_t size)
1665
1666              Makes  a  subbinary  of  binary bin_term, starting at zero-based
1667              position pos with a length of size bytes.  bin_term  must  be  a
1668              binary  or bitstring. pos+size must be less or equal to the num‐
1669              ber of whole bytes in bin_term.
1670
1671       ERL_NIF_TERM enif_make_tuple(ErlNifEnv* env,
1672               unsigned cnt, ...)
1673
1674              Creates a tuple term of arity cnt. Expects cnt number  of  argu‐
1675              ments  (after  cnt)  of type ERL_NIF_TERM as the elements of the
1676              tuple.
1677
1678       ERL_NIF_TERM enif_make_tuple1(ErlNifEnv* env,
1679               ERL_NIF_TERM e1)
1680       ERL_NIF_TERM enif_make_tuple2(ErlNifEnv* env,
1681               ERL_NIF_TERM e1, ERL_NIF_TERM e2)
1682       ERL_NIF_TERM enif_make_tuple3(ErlNifEnv* env,
1683               ERL_NIF_TERM e1, ERL_NIF_TERM e2, ERL_NIF_TERM e3)
1684       ERL_NIF_TERM enif_make_tuple4(ErlNifEnv* env,
1685               ERL_NIF_TERM e1, ..., ERL_NIF_TERM e4)
1686       ERL_NIF_TERM enif_make_tuple5(ErlNifEnv* env,
1687               ERL_NIF_TERM e1, ..., ERL_NIF_TERM e5)
1688       ERL_NIF_TERM enif_make_tuple6(ErlNifEnv* env,
1689               ERL_NIF_TERM e1, ..., ERL_NIF_TERM e6)
1690       ERL_NIF_TERM enif_make_tuple7(ErlNifEnv* env,
1691               ERL_NIF_TERM e1, ..., ERL_NIF_TERM e7)
1692       ERL_NIF_TERM enif_make_tuple8(ErlNifEnv* env,
1693               ERL_NIF_TERM e1, ..., ERL_NIF_TERM e8)
1694       ERL_NIF_TERM enif_make_tuple9(ErlNifEnv* env,
1695               ERL_NIF_TERM e1, ..., ERL_NIF_TERM e9)
1696
1697              Creates a tuple term with length indicated by the function name.
1698              Prefer    these    functions    (macros)   over   the   variadic
1699              enif_make_tuple to get a compile-time error  if  the  number  of
1700              arguments does not match.
1701
1702       ERL_NIF_TERM     enif_make_tuple_from_array(ErlNifEnv*    env,    const
1703       ERL_NIF_TERM
1704               arr[], unsigned cnt)
1705
1706              Creates a tuple containing the elements of array arr  of  length
1707              cnt.
1708
1709       ERL_NIF_TERM enif_make_uint(ErlNifEnv* env, unsigned int i)
1710
1711              Creates an integer term from an unsigned int.
1712
1713       ERL_NIF_TERM enif_make_uint64(ErlNifEnv* env, ErlNifUInt64 i)
1714
1715              Creates an integer term from an unsigned 64-bit integer.
1716
1717       ERL_NIF_TERM enif_make_ulong(ErlNifEnv* env, unsigned long i)
1718
1719              Creates an integer term from an unsigned long int.
1720
1721       ERL_NIF_TERM enif_make_unique_integer(ErlNifEnv
1722               *env, ErlNifUniqueInteger properties)
1723
1724              Returns  a  unique integer with the same properties as specified
1725              by erlang:unique_integer/1.
1726
1727              env is the environment to create the integer in.
1728
1729              ERL_NIF_UNIQUE_POSITIVE  and  ERL_NIF_UNIQUE_MONOTONIC  can   be
1730              passed  as  the  second argument to change the properties of the
1731              integer returned. They can be combined by OR:ing the two  values
1732              together.
1733
1734              See also ErlNifUniqueInteger.
1735
1736       int enif_map_iterator_create(ErlNifEnv *env,
1737               ERL_NIF_TERM map, ErlNifMapIterator *iter, ErlNifMapIteratorEn‐
1738       try
1739               entry)
1740
1741              Creates an iterator for the map map by initializing  the  struc‐
1742              ture  pointed  to  by  iter. Argument entry determines the start
1743              position  of   the   iterator:   ERL_NIF_MAP_ITERATOR_FIRST   or
1744              ERL_NIF_MAP_ITERATOR_LAST.
1745
1746              Returns true on success, or false if map is not a map.
1747
1748              A map iterator is only useful during the lifetime of environment
1749              env that the map belongs to. The iterator must be  destroyed  by
1750              calling enif_map_iterator_destroy:
1751
1752              ERL_NIF_TERM key, value;
1753              ErlNifMapIterator iter;
1754              enif_map_iterator_create(env, my_map, &iter, ERL_NIF_MAP_ITERATOR_FIRST);
1755
1756              while (enif_map_iterator_get_pair(env, &iter, &key, &value)) {
1757                  do_something(key,value);
1758                  enif_map_iterator_next(env, &iter);
1759              }
1760              enif_map_iterator_destroy(env, &iter);
1761
1762          Note:
1763              The  key-value  pairs  of a map have no defined iteration order.
1764              The only guarantee is that the iteration order of a  single  map
1765              instance  is  preserved  during  the lifetime of the environment
1766              that the map belongs to.
1767
1768
1769       void enif_map_iterator_destroy(ErlNifEnv *env,
1770               ErlNifMapIterator *iter)
1771
1772              Destroys a map iterator created by enif_map_iterator_create.
1773
1774       int enif_map_iterator_get_pair(ErlNifEnv *env,
1775               ErlNifMapIterator *iter, ERL_NIF_TERM *key, ERL_NIF_TERM
1776               *value)
1777
1778              Gets key and value terms at the current map iterator position.
1779
1780              On success, sets *key and *value and returns true. Returns false
1781              if  the  iterator  is positioned at head (before first entry) or
1782              tail (beyond last entry).
1783
1784       int enif_map_iterator_is_head(ErlNifEnv *env,
1785               ErlNifMapIterator *iter)
1786
1787              Returns true if map iterator iter is positioned before the first
1788              entry.
1789
1790       int enif_map_iterator_is_tail(ErlNifEnv *env,
1791               ErlNifMapIterator *iter)
1792
1793              Returns  true  if map iterator iter is positioned after the last
1794              entry.
1795
1796       int enif_map_iterator_next(ErlNifEnv *env,
1797               ErlNifMapIterator *iter)
1798
1799              Increments map iterator to point to the next key-value entry.
1800
1801              Returns true if the iterator is now positioned at a  valid  key-
1802              value  entry, or false if the iterator is positioned at the tail
1803              (beyond the last entry).
1804
1805       int enif_map_iterator_prev(ErlNifEnv *env,
1806               ErlNifMapIterator *iter)
1807
1808              Decrements map iterator  to  point  to  the  previous  key-value
1809              entry.
1810
1811              Returns  true  if the iterator is now positioned at a valid key-
1812              value entry, or false if the iterator is positioned at the  head
1813              (before the first entry).
1814
1815       int enif_monitor_process(ErlNifEnv* env, void* obj,
1816             const ErlNifPid* target_pid, ErlNifMonitor* mon)
1817
1818              Starts  monitoring  a process from a resource. When a process is
1819              monitored, a process exit results in a call to the provided down
1820              callback associated with the resource type.
1821
1822              Argument  obj is pointer to the resource to hold the monitor and
1823              *target_pid identifies the local process to be monitored.
1824
1825              If mon is not NULL, a successful call stores the identity of the
1826              monitor  in  the  ErlNifMonitor  struct  pointed to by mon. This
1827              identifier is used to refer to the  monitor  for  later  removal
1828              with  enif_demonitor_process  or compare with enif_compare_moni‐
1829              tors. A monitor is automatically removed  when  it  triggers  or
1830              when the resource is deallocated.
1831
1832              Returns 0 on success, < 0 if no down callback is provided, and >
1833              0 if the process is no longer alive.
1834
1835              This function is only thread-safe when  the  emulator  with  SMP
1836              support  is used. It can only be used in a non-SMP emulator from
1837              a NIF-calling thread.
1838
1839       ErlNifTime enif_monotonic_time(ErlNifTimeUnit time_unit)
1840
1841              Returns the current  Erlang monotonic time. Notice  that  it  is
1842              not uncommon with negative values.
1843
1844              time_unit is the time unit of the returned value.
1845
1846              Returns  ERL_NIF_TIME_ERROR  if called with an invalid time unit
1847              argument, or if called from a thread that  is  not  a  scheduler
1848              thread.
1849
1850              See also ErlNifTime and ErlNifTimeUnit.
1851
1852       ErlNifMutex *enif_mutex_create(char *name)
1853
1854              Same as erl_drv_mutex_create.
1855
1856       void enif_mutex_destroy(ErlNifMutex *mtx)
1857
1858              Same as erl_drv_mutex_destroy.
1859
1860       void enif_mutex_lock(ErlNifMutex *mtx)
1861
1862              Same as erl_drv_mutex_lock.
1863
1864       int enif_mutex_trylock(ErlNifMutex *mtx)
1865
1866              Same as erl_drv_mutex_trylock.
1867
1868       void enif_mutex_unlock(ErlNifMutex *mtx)
1869
1870              Same as erl_drv_mutex_unlock.
1871
1872       ERL_NIF_TERM enif_now_time(ErlNifEnv *env)
1873
1874              Returns an erlang:now() time stamp.
1875
1876              This function is deprecated.
1877
1878       ErlNifResourceType *enif_open_resource_type(ErlNifEnv* env, const char*
1879               module_str, const char* name, ErlNifResourceDtor* dtor,
1880               ErlNifResourceFlags flags, ErlNifResourceFlags* tried)
1881
1882              Creates  or  takes over a resource type identified by the string
1883              name and gives it the destructor function pointed  to  by  dtor.
1884              Argument flags can have the following values:
1885
1886                ERL_NIF_RT_CREATE:
1887                  Creates a new resource type that does not already exist.
1888
1889                ERL_NIF_RT_TAKEOVER:
1890                  Opens  an existing resource type and takes over ownership of
1891                  all its instances. The supplied destructor  dtor  is  called
1892                  both  for  existing instances and new instances not yet cre‐
1893                  ated by the calling NIF library.
1894
1895              The two flag  values  can  be  combined  with  bitwise  OR.  The
1896              resource type name is local to the calling module. Argument mod‐
1897              ule_str is not (yet) used and must be NULL. dtor can be NULL  if
1898              no destructor is needed.
1899
1900              On  success, the function returns a pointer to the resource type
1901              and   *tried   is   set   to   either    ERL_NIF_RT_CREATE    or
1902              ERL_NIF_RT_TAKEOVER  to  indicate  what  was  done.  On failure,
1903              returns NULL and sets *tried to flags.  It  is  allowed  to  set
1904              tried to NULL.
1905
1906              Notice that enif_open_resource_type is only allowed to be called
1907              in the two callbacks load and upgrade.
1908
1909              See also enif_open_resource_type_x.
1910
1911       ErlNifResourceType  *enif_open_resource_type_x(ErlNifEnv*  env,   const
1912       char* name,      const ErlNifResourceTypeInit* init,
1913               ErlNifResourceFlags flags, ErlNifResourceFlags* tried)
1914
1915              Same  as  enif_open_resource_type  except  it accepts additional
1916              callback functions for resource types  that  are  used  together
1917              with enif_select and enif_monitor_process.
1918
1919              Argument  init  is a pointer to an ErlNifResourceTypeInit struc‐
1920              ture that contains the function pointers  for  destructor,  down
1921              and stop callbacks for the resource type.
1922
1923       int enif_port_command(ErlNifEnv* env, const
1924              ErlNifPort* to_port, ErlNifEnv *msg_env, ERL_NIF_TERM msg)
1925
1926              Works  as  erlang:port_command/2,  except that it is always com‐
1927              pletely asynchronous.
1928
1929                env:
1930                  The environment of the calling process. Must not be NULL.
1931
1932                *to_port:
1933                  The port ID of the receiving port. The port ID is  to  refer
1934                  to a port on the local node.
1935
1936                msg_env:
1937                  The  environment of the message term. Can be a process-inde‐
1938                  pendent environment allocated with enif_alloc_env or NULL.
1939
1940                msg:
1941                  The message term to send. The same limitations apply  as  on
1942                  the payload to erlang:port_command/2.
1943
1944              Using  a  msg_env  of  NULL  is  an  optimization,  which groups
1945              together calls to enif_alloc_env, enif_make_copy, enif_port_com‐
1946              mand, and enif_free_env into one call. This optimization is only
1947              useful when a majority of the terms are to be copied from env to
1948              msg_env.
1949
1950              Returns  true if the command is successfully sent. Returns false
1951              if the command fails, for example:
1952
1953                * *to_port does not refer to a local port.
1954
1955                * The currently executing process (that is, the sender) is not
1956                  alive.
1957
1958                * msg is invalid.
1959
1960              See also enif_get_local_port.
1961
1962       void *enif_priv_data(ErlNifEnv* env)
1963
1964              Returns  the pointer to the private data that was set by load or
1965              upgrade.
1966
1967       ERL_NIF_TERM enif_raise_exception(ErlNifEnv*
1968               env, ERL_NIF_TERM reason)
1969
1970              Creates an error exception with the term reason to  be  returned
1971              from  a  NIF, and associates it with environment env. Once a NIF
1972              or any function it calls invokes enif_raise_exception, the  run‐
1973              time  ensures  that  the exception it creates is raised when the
1974              NIF returns, even if the NIF attempts to return a  non-exception
1975              term instead.
1976
1977              The  return  value from enif_raise_exception can only be used as
1978              the return value from the NIF that invoked it (directly or indi‐
1979              rectly)  or be passed to enif_is_exception, but not to any other
1980              NIF API function.
1981
1982              See also enif_has_pending_exception and enif_make_badarg.
1983
1984       void *enif_realloc(void* ptr, size_t size)
1985
1986              Reallocates memory allocated by enif_alloc to size bytes.
1987
1988              Returns NULL if the reallocation fails.
1989
1990              The returned pointer is suitably aligned for any  built-in  type
1991              that fit in the allocated memory.
1992
1993       int enif_realloc_binary(ErlNifBinary* bin, size_t size)
1994
1995              Changes the size of a binary bin. The source binary can be read-
1996              only, in which case it is left untouched and a mutable  copy  is
1997              allocated and assigned to *bin.
1998
1999              Returns true on success, or false if memory allocation failed.
2000
2001       void enif_release_binary(ErlNifBinary* bin)
2002
2003              Releases a binary obtained from enif_alloc_binary.
2004
2005       void enif_release_resource(void* obj)
2006
2007              Removes  a  reference  to  resource  object  obj  obtained  from
2008              enif_alloc_resource. The resource object is destructed when  the
2009              last  reference  is  removed. Each call to enif_release_resource
2010              must correspond to a previous  call  to  enif_alloc_resource  or
2011              enif_keep_resource.  References  made  by enif_make_resource can
2012              only be removed by the garbage collector.
2013
2014       ErlNifRWLock *enif_rwlock_create(char *name)
2015
2016              Same as erl_drv_rwlock_create.
2017
2018       void enif_rwlock_destroy(ErlNifRWLock *rwlck)
2019
2020              Same as erl_drv_rwlock_destroy.
2021
2022       void enif_rwlock_rlock(ErlNifRWLock *rwlck)
2023
2024              Same as erl_drv_rwlock_rlock.
2025
2026       void enif_rwlock_runlock(ErlNifRWLock *rwlck)
2027
2028              Same as erl_drv_rwlock_runlock.
2029
2030       void enif_rwlock_rwlock(ErlNifRWLock *rwlck)
2031
2032              Same as erl_drv_rwlock_rwlock.
2033
2034       void enif_rwlock_rwunlock(ErlNifRWLock *rwlck)
2035
2036              Same as erl_drv_rwlock_rwunlock.
2037
2038       int enif_rwlock_tryrlock(ErlNifRWLock *rwlck)
2039
2040              Same as erl_drv_rwlock_tryrlock.
2041
2042       int enif_rwlock_tryrwlock(ErlNifRWLock *rwlck)
2043
2044              Same as erl_drv_rwlock_tryrwlock.
2045
2046       ERL_NIF_TERM enif_schedule_nif(ErlNifEnv* env,
2047               const char* fun_name, int flags, ERL_NIF_TERM  (*fp)(ErlNifEnv*
2048       env, int
2049               argc, const ERL_NIF_TERM argv[]), int argc, const ERL_NIF_TERM
2050               argv[])
2051
2052              Schedules NIF fp to execute. This function allows an application
2053              to break up long-running work into multiple regular NIF calls or
2054              to schedule a  dirty NIF to execute on a dirty scheduler thread.
2055
2056                fun_name:
2057                  Provides a name for the NIF that is scheduled for execution.
2058                  If it cannot be  converted  to  an  atom,  enif_schedule_nif
2059                  returns a badarg exception.
2060
2061                flags:
2062                  Must  be  set  to  0  for a regular NIF. If the emulator was
2063                  built with dirty scheduler support enabled, flags can be set
2064                  to either ERL_NIF_DIRTY_JOB_CPU_BOUND if the job is expected
2065                  to be CPU-bound, or ERL_NIF_DIRTY_JOB_IO_BOUND for jobs that
2066                  will be I/O-bound. If dirty scheduler threads are not avail‐
2067                  able in the emulator, an attempt  to  schedule  such  a  job
2068                  results in a notsup exception.
2069
2070                argc and argv:
2071                  Can  either be the originals passed into the calling NIF, or
2072                  can be values created by the calling NIF.
2073
2074              The calling NIF must use the return value  of  enif_schedule_nif
2075              as its own return value.
2076
2077              Be  aware  that  enif_schedule_nif,  as  its  name implies, only
2078              schedules the NIF for future execution. The calling NIF does not
2079              block  waiting for the scheduled NIF to execute and return. This
2080              means that the calling NIF cannot expect to receive  the  sched‐
2081              uled NIF return value and use it for further operations.
2082
2083       int  enif_select(ErlNifEnv*  env, ErlNifEvent event, enum ErlNifSelect‐
2084       Flags mode,      void* obj, const ErlNifPid* pid, ERL_NIF_TERM ref)
2085
2086              This function can be used to receive asynchronous  notifications
2087              when  OS-specific  event objects become ready for either read or
2088              write operations.
2089
2090              Argument event identifies the event object. On Unix systems, the
2091              functions  select/poll  are  used.  The  event  object must be a
2092              socket, pipe or other file descriptor  object  that  select/poll
2093              can use.
2094
2095              Argument  mode  describes the type of events to wait for. It can
2096              be ERL_NIF_SELECT_READ, ERL_NIF_SELECT_WRITE  or  a  bitwise  OR
2097              combination to wait for both. It can also be ERL_NIF_SELECT_STOP
2098              which is described further below. When a read or write event  is
2099              triggerred,  a  notification  message  like  this is sent to the
2100              process identified by pid:
2101
2102              {select, Obj, Ref, ready_input | ready_output}
2103
2104              ready_input or ready_output indicates if  the  event  object  is
2105              ready for reading or writing.
2106
2107              Argument pid may be NULL to indicate the calling process.
2108
2109              Argument    obj    is    a   resource   object   obtained   from
2110              enif_alloc_resource. The purpose of the resource objects is as a
2111              container  of the event object to manage its state and lifetime.
2112              A handle to the resource is received in the notification message
2113              as Obj.
2114
2115              Argument   ref   must   be  either  a  reference  obtained  from
2116              erlang:make_ref/0 or the atom undefined. It will  be  passed  as
2117              Ref  in  the  notifications. If a selective receive statement is
2118              used to wait for the notification then a reference created  just
2119              before  the  receive  will  exploit  a runtime optimization that
2120              bypasses all earlier received messages in the queue.
2121
2122              The notifications are one-shot only. To receive further  notifi‐
2123              cations  of  the  same  type  (read or write), repeated calls to
2124              enif_select must be made after receiving each notification.
2125
2126              Use ERL_NIF_SELECT_STOP as mode in  order  to  safely  close  an
2127              event object that has been passed to enif_select. The stop call‐
2128              back of the resource obj will be called when it is safe to close
2129              the event object. This safe way of closing event objects must be
2130              used even if all notifications have been received and no further
2131              calls to enif_select have been made.
2132
2133              The  first  call  to  enif_select  for  a specific OS event will
2134              establish a relation between the event object and the containing
2135              resource.  All  subsequent calls for an event must pass its con‐
2136              taining resource as argument obj. The relation is dissolved when
2137              enif_select has been called with mode as ERL_NIF_SELECT_STOP and
2138              the corresponding stop callback has  returned.  A  resource  can
2139              contain  several  event objects but one event object can only be
2140              contained within one resource. A resource will not be destructed
2141              until all its contained relations have been dissolved.
2142
2143          Note:
2144              Use  enif_monitor_process  together  with  enif_select to detect
2145              failing Erlang processes and prevent them from causing permanent
2146              leakage of resources and their contained OS event objects.
2147
2148
2149              Returns a non-negative value on success where the following bits
2150              can be set:
2151
2152                ERL_NIF_SELECT_STOP_CALLED:
2153                  The stop callback was called directly by enif_select.
2154
2155                ERL_NIF_SELECT_STOP_SCHEDULED:
2156                  The stop callback was scheduled to run on some other  thread
2157                  or later by this thread.
2158
2159              Returns  a  negative value if the call failed where the follwing
2160              bits can be set:
2161
2162                ERL_NIF_SELECT_INVALID_EVENT:
2163                  Argument event is not a valid OS event object.
2164
2165                ERL_NIF_SELECT_FAILED:
2166                  The system call failed to add the event object to  the  poll
2167                  set.
2168
2169          Note:
2170              Use  bitwise  AND  to test for specific bits in the return vaue.
2171              New significant bits may be added in  future  releases  to  give
2172              more  detailed information for both failed and successful calls.
2173              Do NOT use equallity tests like  ==,  as  that  may  cause  your
2174              application to stop working.
2175
2176              Example:
2177
2178              retval = enif_select(env, fd, ERL_NIF_SELECT_STOP, resource, ref);
2179              if (retval < 0) {
2180                  /* handle error */
2181              }
2182              /* Success! */
2183              if (retval & ERL_NIF_SELECT_STOP_CALLED) {
2184                  /* ... */
2185              }
2186
2187
2188
2189       ErlNifPid *enif_self(ErlNifEnv* caller_env, ErlNifPid* pid)
2190
2191              Initializes  the  ErlNifPid  variable  at  *pid to represent the
2192              calling process.
2193
2194              Returns pid if successful,  or  NULL  if  caller_env  is  not  a
2195              process-bound environment.
2196
2197       int enif_send(ErlNifEnv* env, ErlNifPid* to_pid,
2198               ErlNifEnv* msg_env, ERL_NIF_TERM msg)
2199
2200              Sends a message to a process.
2201
2202                env:
2203                  The environment of the calling process. Must be NULL only if
2204                  calling from a created thread.
2205
2206                *to_pid:
2207                  The pid of the receiving process. The pid is to refer  to  a
2208                  process on the local node.
2209
2210                msg_env:
2211                  The environment of the message term. Must be a process-inde‐
2212                  pendent environment allocated with enif_alloc_env or NULL.
2213
2214                msg:
2215                  The message term to send.
2216
2217              Returns true if the message is successfully sent. Returns  false
2218              if the send operation fails, that is:
2219
2220                * *to_pid does not refer to an alive local process.
2221
2222                * The currently executing process (that is, the sender) is not
2223                  alive.
2224
2225              The message environment msg_env with all  its  terms  (including
2226              msg) is invalidated by a successful call to enif_send. The envi‐
2227              ronment is to either be freed with enif_free_env of cleared  for
2228              reuse with enif_clear_env.
2229
2230              If msg_env is set to NULL, the msg term is copied and the origi‐
2231              nal term and its environemt is still valid after the call.
2232
2233              This function is only thread-safe when  the  emulator  with  SMP
2234              support  is used. It can only be used in a non-SMP emulator from
2235              a NIF-calling thread.
2236
2237          Note:
2238              Passing msg_env as NULL is  only  supported  as  from  ERTS  8.0
2239              (Erlang/OTP 19).
2240
2241
2242       unsigned enif_sizeof_resource(void* obj)
2243
2244              Gets   the   byte  size  of  resource  object  obj  obtained  by
2245              enif_alloc_resource.
2246
2247       int enif_snprintf(char *str, size_t size, const
2248               char *format, ...)
2249
2250              Similar to snprintf but this format string  also  accepts  "%T",
2251              which formats Erlang terms.
2252
2253       void enif_system_info(ErlNifSysInfo
2254               *sys_info_ptr, size_t size)
2255
2256              Same as driver_system_info.
2257
2258       int enif_term_to_binary(ErlNifEnv *env,
2259               ERL_NIF_TERM term, ErlNifBinary *bin)
2260
2261              Allocates  a  new  binary  with enif_alloc_binary and stores the
2262              result of encoding term according to the  Erlang  external  term
2263              format.
2264
2265              Returns true on success, or false if the allocation fails.
2266
2267              See also erlang:term_to_binary/1 and enif_binary_to_term.
2268
2269       int enif_thread_create(char *name,ErlNifTid
2270               *tid,void * (*func)(void *),void *args,ErlNifThreadOpts
2271               *opts)
2272
2273              Same as erl_drv_thread_create.
2274
2275       void enif_thread_exit(void *resp)
2276
2277              Same as erl_drv_thread_exit.
2278
2279       int enif_thread_join(ErlNifTid, void **respp)
2280
2281              Same as erl_drv_thread_join.
2282
2283       ErlNifThreadOpts *enif_thread_opts_create(char *name)
2284
2285              Same as erl_drv_thread_opts_create.
2286
2287       void enif_thread_opts_destroy(ErlNifThreadOpts *opts)
2288
2289              Same as erl_drv_thread_opts_destroy.
2290
2291       ErlNifTid enif_thread_self(void)
2292
2293              Same as erl_drv_thread_self.
2294
2295       int enif_thread_type(void)
2296
2297              Determine  the  type  of  currently executing thread. A positive
2298              value indicates a scheduler thread while  a  negative  value  or
2299              zero  indicates  another type of thread. Currently the following
2300              specific types exist (which may be extended in the future):
2301
2302                ERL_NIF_THR_UNDEFINED:
2303                  Undefined thread that is not a scheduler thread.
2304
2305                ERL_NIF_THR_NORMAL_SCHEDULER:
2306                  A normal scheduler thread.
2307
2308                ERL_NIF_THR_DIRTY_CPU_SCHEDULER:
2309                  A dirty CPU scheduler thread.
2310
2311                ERL_NIF_THR_DIRTY_IO_SCHEDULER:
2312                  A dirty I/O scheduler thread.
2313
2314       ErlNifTime enif_time_offset(ErlNifTimeUnit time_unit)
2315
2316              Returns the current time offset between  Erlang  monotonic  time
2317              and   Erlang  system time converted into the time_unit passed as
2318              argument.
2319
2320              time_unit is the time unit of the returned value.
2321
2322              Returns ERL_NIF_TIME_ERROR if called with an invalid  time  unit
2323              argument  or  if  called  from  a thread that is not a scheduler
2324              thread.
2325
2326              See also ErlNifTime and ErlNifTimeUnit.
2327
2328       void *enif_tsd_get(ErlNifTSDKey key)
2329
2330              Same as erl_drv_tsd_get.
2331
2332       int enif_tsd_key_create(char *name, ErlNifTSDKey *key)
2333
2334              Same as erl_drv_tsd_key_create.
2335
2336       void enif_tsd_key_destroy(ErlNifTSDKey key)
2337
2338              Same as erl_drv_tsd_key_destroy.
2339
2340       void enif_tsd_set(ErlNifTSDKey key, void *data)
2341
2342              Same as erl_drv_tsd_set.
2343
2344       int enif_whereis_pid(ErlNifEnv *env,
2345                 ERL_NIF_TERM name, ErlNifPid *pid)
2346
2347              Looks up a process by its registered name.
2348
2349                env:
2350                  The environment of the calling process. Must be NULL only if
2351                  calling from a created thread.
2352
2353                name:
2354                  The name of a registered process, as an atom.
2355
2356                *pid:
2357                  The ErlNifPid in which the resolved process id is stored.
2358
2359              On  success, sets *pid to the local process registered with name
2360              and returns true. If name is not a registered process, or is not
2361              an atom, false is returned and *pid is unchanged.
2362
2363              Works  as  erlang:whereis/1,  but  restricted  to processes. See
2364              enif_whereis_port to resolve registered ports.
2365
2366       int enif_whereis_port(ErlNifEnv *env,
2367                 ERL_NIF_TERM name, ErlNifPort *port)
2368
2369              Looks up a port by its registered name.
2370
2371                env:
2372                  The environment of the calling process. Must be NULL only if
2373                  calling from a created thread.
2374
2375                name:
2376                  The name of a registered port, as an atom.
2377
2378                *port:
2379                  The ErlNifPort in which the resolved port id is stored.
2380
2381              On  success,  sets  *port  to  the port registered with name and
2382              returns true. If name is not a registered port,  or  is  not  an
2383              atom, false is returned and *port is unchanged.
2384
2385              Works   as   erlang:whereis/1,  but  restricted  to  ports.  See
2386              enif_whereis_pid to resolve registered processes.
2387

SEE ALSO

2389       erlang:load_nif/2
2390
2391
2392
2393Ericsson AB                      erts 9.3.3.10                      erl_nif(3)
Impressum