[erlang-questions] driver_output_term, driver_send_term and ei

Serge Aleynikov saleyn@REDACTED
Fri Aug 31 04:55:39 CEST 2007

Joel Reymont wrote:
> It seems that the erl_driver docs recommend using driver_output_term  
> for efficiency reason.

That is compared to ei and the driver_output{2,v} family of functions as 
there's no extra copying involved in the former.

> I noticed that Klacke uses driver_send_term in his posregex linked-in  
> driver. Would driver_output_term work just as well if the driver was  
> given the pid of the caller to be given back to the port owner process?
> Generally speaking, are there guidelines for when to use each function?

It depends on your application's architecture.  If you marshal all 
interface with the driver through Erlang's middleman gen_server process, 
then you would want to use driver_output_term to pass data to port owner 
process that would send a reply back to the caller.  Alternatively, if 
you allow other processes to communicate with the driver directly, use 
driver_caller and driver_send_term.

Also be extra careful as driver_output_term is not thread-safe and 
driver_send_term is only thread-safe when SMP is used.  So either 
function should be called from within the context of the emulator's 
thread (e.g. in body of driver_entry's callbacks).

> Should I use term_to_binary nowadays to send data to the driver, ei  
> to decode in the driver and driver_output_term to send back?

While you can use ei, you don't need to or else pay performance penalty. 
  The fastest way to deliver data back to Erlang is to use 
ErlDrvTermData stucts and LOAD_ATOM/TUPLE/PORT/etc macros (see 
inet_drv.c in distribution) to populate the structures and use 
driver_send_term / driver_output_term for delivery.  This avoids extra 
binary conversion and data is received by an Erlang process as a term.

When calling C code from Erlang using erlang:port_call/3 or 
erlang:port_command/2 external binary term format is used, so ei can be 
used to decode data.  A convenience of port_call/3 is that you can pass 
a term "as is" whereas port_command/2 requires you to convert a term to 
binary (or iolist()) yourself.


More information about the erlang-questions mailing list