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_ioq_peek_head()
298
299           * enif_inspect_iovec()
300
301           * enif_free_iovec()
302
303           Typical usage when writing to a file descriptor looks like this:
304
305         int writeiovec(ErlNifEnv *env, ERL_NIF_TERM term, ERL_NIF_TERM *tail,
306                        ErlNifIOQueue *q, int fd) {
307
308             ErlNifIOVec vec, *iovec = &vec;
309             SysIOVec *sysiovec;
310             int saved_errno;
311             int iovcnt, n;
312
313             if (!enif_inspect_iovec(env, 64, term, tail, &iovec))
314                 return -2;
315
316             if (enif_ioq_size(q) > 0) {
317                 /* If the I/O queue contains data we enqueue the iovec and
318                    then peek the data to write out of the queue. */
319                 if (!enif_ioq_enqv(q, iovec, 0))
320                     return -3;
321
322                 sysiovec = enif_ioq_peek(q, &iovcnt);
323             } else {
324                 /* If the I/O queue is empty we skip the trip through it. */
325                 iovcnt = iovec->iovcnt;
326                 sysiovec = iovec->iov;
327             }
328
329             /* Attempt to write the data */
330             n = writev(fd, sysiovec, iovcnt);
331             saved_errno = errno;
332
333             if (enif_ioq_size(q) == 0) {
334                 /* If the I/O queue was initially empty we enqueue any
335                    remaining data into the queue for writing later. */
336                 if (n >= 0 && !enif_ioq_enqv(q, iovec, n))
337                     return -3;
338             } else {
339                 /* Dequeue any data that was written from the queue. */
340                 if (n > 0 && !enif_ioq_deq(q, n, NULL))
341                     return -4;
342             }
343
344             /* return n, which is either number of bytes written or -1 if
345                some error happened */
346             errno = saved_errno;
347             return n;
348         }
349
350         Long-running NIFs:
351           As  mentioned  in  the warning text at the beginning of this manual
352           page, it is of vital importance that a native function returns rel‐
353           atively  fast.  It  is difficult to give an exact maximum amount of
354           time that a native function is allowed to work, but usually a well-
355           behaving  native  function is to return to its caller within 1 mil‐
356           lisecond. This can be achieved using different approaches.  If  you
357           have  full control over the code to execute in the native function,
358           the best approach is to divide the work  into  multiple  chunks  of
359           work and call the native function multiple times. This is, however,
360           not  always  possible,  for  example   when   calling   third-party
361           libraries.
362
363           The  enif_consume_timeslice()  function  can  be used to inform the
364           runtime system about the length of the NIF call.  It  is  typically
365           always to be used unless the NIF executes very fast.
366
367           If  the NIF call is too lengthy, this must be handled in one of the
368           following ways to avoid  degraded  responsiveness,  scheduler  load
369           balancing problems, and other strange behaviors:
370
371           Yielding NIF:
372             If  the  functionality of a long-running NIF can be split so that
373             its work can be achieved through a series of shorter  NIF  calls,
374             the application has two options:
375
376             * Make that series of NIF calls from the Erlang level.
377
378             * Call  a  NIF  that  first  performs  a  chunk of the work, then
379               invokes the enif_schedule_nif function to schedule another  NIF
380               call  to  perform  the  next chunk. The final call scheduled in
381               this manner can then return the overall result.
382
383             Breaking up a long-running function in this manner enables the VM
384             to regain control between calls to the NIFs.
385
386             This  approach  is  always  preferred over the other alternatives
387             described below. This both from a performance perspective  and  a
388             system characteristics perspective.
389
390           Threaded NIF:
391             This  is  accomplished  by dispatching the work to another thread
392             managed by the NIF library, return from the NIF, and wait for the
393             result. The thread can send the result back to the Erlang process
394             using enif_send. Information about thread primitives is  provided
395             below.
396
397           Dirty NIF:
398
399
400       Note:
401           Dirty NIF support is available only when the emulator is configured
402           with dirty scheduler support. As of ERTS version 9.0, dirty  sched‐
403           uler  support  is enabled by default on the runtime system with SMP
404           support. The Erlang runtime without SMP support  does  not  support
405           dirty  schedulers  even when the dirty scheduler support is explic‐
406           itly enabled. To check at runtime for the presence of dirty  sched‐
407           uler threads, code can use the enif_system_info() API function.
408
409
410             A NIF that cannot be split and cannot execute in a millisecond or
411             less is called a "dirty NIF", as it performs work that the  ordi‐
412             nary  schedulers  of  the  Erlang  runtime  system  cannot handle
413             cleanly. Applications that make use of such functions must  indi‐
414             cate  to  the runtime that the functions are dirty so they can be
415             handled specially. This is handled by executing dirty jobs  on  a
416             separate  set  of schedulers called dirty schedulers. A dirty NIF
417             executing on a dirty scheduler does not have  the  same  duration
418             restriction as a normal NIF.
419
420             It  is  important to classify the dirty job correct. An I/O bound
421             job should be classified as such, and a CPU bound job  should  be
422             classified  as such. If you should classify CPU bound jobs as I/O
423             bound jobs, dirty I/O schedulers  might  starve  ordinary  sched‐
424             ulers.  I/O  bound  jobs are expected to either block waiting for
425             I/O, and/or spend a limited amount of time moving data.
426
427             To schedule a dirty NIF for execution, the  application  has  two
428             options:
429
430             * Set  the  appropriate flags value for the dirty NIF in its Erl‐
431               NifFunc entry.
432
433             * Call enif_schedule_nif, pass to it a pointer to the  dirty  NIF
434               to  be  executed,  and  indicate with argument flags whether it
435               expects the operation to be CPU-bound or I/O-bound.
436
437             A job that alternates between I/O bound  and  CPU  bound  can  be
438             reclassified  and  rescheduled using enif_schedule_nif so that it
439             executes on the correct type of dirty scheduler at all times. For
440             more information see the documentation of the erl(1) command line
441             arguments +SDcpu, and +SDio.
442
443             While a process executes a dirty NIF, some operations that commu‐
444             nicate  with it can take a very long time to complete. Suspend or
445             garbage collection of a process executing a dirty NIF  cannot  be
446             done  until  the  dirty  NIF  has returned. Thus, other processes
447             waiting for such operations to complete might have to wait for  a
448             very  long  time.  Blocking  multi-scheduling,  that  is, calling
449             erlang:system_flag(multi_scheduling, block), can also take a very
450             long  time  to complete. This is because all ongoing dirty opera‐
451             tions on all dirty schedulers  must  complete  before  the  block
452             operation can complete.
453
454             Many  operations  communicating  with a process executing a dirty
455             NIF can, however, complete while it executes the dirty  NIF.  For
456             example,     retrieving     information    about    it    through
457             erlang:process_info, setting its group leader,  register/unregis‐
458             ter its name, and so on.
459
460             Termination  of  a process executing a dirty NIF can only be com‐
461             pleted up to a certain point while it executes the dirty NIF. All
462             Erlang resources, such as its registered name and its ETS tables,
463             are released. All links and monitors are triggered. The execution
464             of  the NIF is, however, not stopped. The NIF can safely continue
465             execution, allocate heap memory, and so on, but it is  of  course
466             better  to  stop executing as soon as possible. The NIF can check
467             whether  a  current   process   is   alive   using   enif_is_cur‐
468             rent_process_alive.    Communication    using    enif_send    and
469             enif_port_command is also dropped when the sending process is not
470             alive.  Deallocation  of  certain  internal  resources,  such  as
471             process heap and process control  block,  is  delayed  until  the
472             dirty NIF has completed.
473

INITIALIZATION

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

DATA TYPES

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

EXPORTS

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

SEE ALSO

2473       erlang:load_nif/2
2474
2475
2476
2477Ericsson AB                      erts 10.3.5.2                      erl_nif(3)
Impressum