How to use NIF to interact with C code that keeps state across calls (i.e., linked lists as NIF)

759 views Asked by At

I wanted to create a linked-list data structure that was implemented in C. The idea was that one would create a linked list

ll:new() -> listId.

ListId, above, represents a "pointer" of some type that would get passed back to the C code which would function as some type of handle on the list. I was hoping not to have to pass the list itself back and forth since I imagined lists could get very, very large. Once the linked list was created, users would then interact with it in obvious ways:

ll:add(ListId, Elt)
ll:add_after(ListId, Pos, Elt)

I imagined I would do this via Erlang's NIF capabilities. Now, for this to work the C side has to maintain the list across multiple calls to add, add_after, etc.

In straight C, I would have a main function that a user interacts with that would keep the program alive thereby keeping the linked list persisted for the life of the user's interaction with the program. As I understand it, NIFs utilizes C code with no main function. That is, that each call to a NIF is a one-and-done type of proposition.

Can someone give me some pointers on how (assuming it is appropriate) one can utilize NIFs to interact with C code that needs keeps state across multiple calls? I hope that was clear!

2

There are 2 answers

0
Lukas On BEST ANSWER

Check the documentation for resource objects. The NIF API even allows you to use the erlang GC to GC the lists you create should the process which has created it crash!

0
Odobenus Rosmarus On

the 'static' variable in C can keep value between calls, but I would strongly dont recommend this way. If you need some state, it would be better to look at 'ports' in erlang.