Use cases for port drivers - when is it better to use a port driver instead of a NIF?

Hi there,

what are the cases when it’s better to use a port driver instead of a NIF? Actually, are there any?

3 Likes

Actually port drivers is the old solution and our intention is that NIFs can be used instead of port drivers for all use cases. We don’t recommend writing new code with the port driver concept use NIFs instead.
In the not so near future we might remove support for port drivers.

11 Likes

Very interesting intention!

Sorry to digging up this old thread, but could you please explain how to use NIF for stateful approaches?

In port driver you allocate some object (state-like) in driver_start entry point, and return it. And all further port driver calls have this state-object.
If it move to NIF, now I have to create state term (for example or resource), return it back and manage this object passes to every call as one of a parameters, i guess?

Yes, that’s it. Similar to how you have to pass the port as argument to every call into the driver.

If your state holds some precious OS/hardware resource such as a TCP connection you probably also want to have one or more owning Erlang processes by letting the NIF resource monitor those processes (enif_monitor_process). Then you can release your OS resource in the down callback if the owning process(es) terminates/crashes. To only rely on the destructor of the NIF resource can be risky as that will get you dependent on when the garbage collector will be invoked and actually find the very last reference to your resource.
If your state is only some memory then relying only on the GC is probably fine.

1 Like

Do you have already planned this into some of further releases? Because right now I made some port driver and after this topic think about rewrite it to this concept )

“this”?
enif_monitor_process exists since OTP 20.0.
Removing support for port drivers has no planned release set.

Yes, I asked about removing port drivers.
Thank you for clarification