[erlang-questions] Term to binary in a NIF
Michael Santos
michael.santos@REDACTED
Mon Feb 13 19:00:41 CET 2012
On Mon, Feb 13, 2012 at 11:56:55AM -0500, Matthew Evans wrote:
>
> Hi
> I've written a NIF that takes data from an external device driver, converts it to a term (a tuple) and uses enif_send (from a thread created by the nif) to a specific Erlang process.
> Unfortunately on some deployments we have been forced to disable SMP in the Linux kernel and BEAM due to a third-party driver issue. In these cases what I have done is used enif_system_info in the NIF, and if SMP is disabled I will send the message via a unix domain socket (I have a driver for that) instead of enif_send.
An alternative would be using a port driver.
> On the Erlang side the UDS is opened, and I use erlang:open_port to pass the unix domain socket to the event loop. What is nice here is that I can use the same Erlang and C code for both SMP enabled and disabled systems. So the Erlang process would get an Erlang message like:
> {driver_result,Integer,Integer} - If SMP is enabled
> Or:
> {#Port<0.647>,{data,SomeBinary}} - If SMP is disabled
> What I would like to do is see if I can send the message as an Erlang term to the unix domain socket using something like term_to_binary in the NIF (I would prefer that instead of sending raw binary to Erlang with enif_send).
> Is that possible?
You can do the encoding using ei or manually create the binary using
the external term format, e.g.:
1> term_to_binary(foo).
<<131,100,0,3,102,111,111>>
131 = magic
100 = atom
0 3 = 3 bytes
102 111 111 = foo
More information about the erlang-questions
mailing list