What I was never able to wrap my head around with NIFs was lifecycles and ownership. The entire "resource" thing always confused me a little.
Say I wanted to implement my own ETS, maybe to add an atomic rename (which ETS really should have). Like ETS, I'd like to have a :named_table, so I don't need to pass a `ref` around everywhere. How/where do I create this global table lookup and how/who manages it?
For lifecycles, BEAM calls your NIF's load/upgrade/unload hooks as appropriate.
For global NIF module data, you're steered towards setting it up in the priv_data pointer passed to those hooks, and retreivable with enif_priv_data, but you can also use static variables or whatever else (it is native code, BEAM can't force you to do anything).
Lifecycle of Erlang Terms is bound to environments, often NIFs get Erlang Terms from the process that called them, and return Erlang Terms to that process... You can't keep references to those in native variables beyond the scope of the function call though; if you need to keep things around, you've got to either copy the values directly into native values, or use erl_make_copy to copy to an environment that you manage. (The erl_nif manpage is probably more clear than me, look for ErlNifEnv)
All that said, I think you're looking for a multi-table atomic rename like in MySQL[1]; so that you can replace a table in a single transaction? If that's all you want to change, you probably should just modify ets, rather than reimplement all the things; I'd be somewhat concerned about adding additional locking, but I don't know what the existing locking looks like.
You can put your nif ref into a persistent term (if you do not plan to update it).
Or into ETS table (which kinda defeats the purpose of making your own ETS table).
But probably you would wanna not use resources and pass name of a table as an atom into your C level.
Lifecycle is simple, the same lifecycle is as for long binaries. Each process that saw the reference would increase internal ref count. Once a process has been GC-d and does not have references to the resource in the process heap - the ref count decreases. When nobody references the resource - it is removed.
Say I wanted to implement my own ETS, maybe to add an atomic rename (which ETS really should have). Like ETS, I'd like to have a :named_table, so I don't need to pass a `ref` around everywhere. How/where do I create this global table lookup and how/who manages it?