[erlang-questions] question about NIF resources
Sverker Eriksson
sverker@REDACTED
Mon Jan 3 12:36:49 CET 2011
Michael Santos wrote:
> The documentation is quite explicit about the behaviour of
> enif_make_resource():
>
> "The term returned by enif_make_resource is totally opaque in nature. It
> can be stored and passed between processses on the same node, but the
> only real end usage is to pass it back as argument to a NIF.
> <...>
> Other operations such as matching or term_to_binary will have
> unpredictable (but harmless) results."
>
> That's clear enough but I wonder if unpredictable behaviour is really
> harmless or if I'm confused about how it works. For example, with an
> NIF wrapping malloc() [1] such as:
>
>
"Harmless" only in the sense that it will not crash your VM. You will
get an Erlangish result, but unpredictable. In other words: Dont do it!
In current implementation, resource terms look and behave like empty
binaries. Matching is thus pointless. It's on the ToDo list to implement
matching.
But even if the resource terms look alike, they are unique and there is
no bug leaking NIF resources (that I know of). A resource is released
(and destructor called) when the last reference is garbage collected.
The shell can fool you however, as it keeps a command history that can
retain terms even though you think the variables are forgotten. Test NIF
resource cleanup by running a test module and call
erlang:garbage_collect to force destructors to be called.
/Sverker, Erlang/OTP
More information about the erlang-questions
mailing list