AtomVM icon indicating copy to clipboard operation
AtomVM copied to clipboard

question: howto return a void* from a nif.

Open elsbiet opened this issue 6 months ago • 3 comments

hello,

what would be the best way to return a void* (which will be an input parameter of other nif(s) ) from a nif?

thanks for any answer.

elsbiet avatar Jul 02 '25 06:07 elsbiet

Same with BEAM, the best is to create a resource if void* is a malloc zone that needs to be freed when it's no longer referenced, otherwise you would risk a leak.

Resources are ref counted and destructor is called when the reference counter reaches 0.

Resources in AtomVM currently appear as zero-length binaries as it used to do with BEAM OTP21. This is a limitation because I wasn't aware of resources as references that were introduced later in BEAM and we need to catch up as references are superior for matching. Meanwhile you might need a reference to distinguish resources.

pguyot avatar Jul 02 '25 07:07 pguyot

thanks for your answer,

memory leaks are not a problem in my use case because resources are allocated at startup and will live 'forever'. the void* points to an object of an unknown structure which would have to be destroyed - a simple free is not enough. in order to call the destructor i would implement a nif which would call the destructor, use a try - catch - after construct and call the destructing nif in the after block.

anyway ..

how would i retrieve the void* from a resource? what would be the 'term function'?

e.

elsbiet avatar Jul 03 '25 12:07 elsbiet

If you have NIF that takes a resource reference, you can use enif_get_resource, cast it, and extract your data from the registered struct.

jgonet avatar Jul 07 '25 13:07 jgonet