This section outlines an example of how to solve the example
problem in
The following example shows an Erlang program communicating with a C program over a plain port with home made encoding:
There are two differences when using Erl_Interface on the C
side compared to the example in
That is:
open_port({spawn, ExtPrg}, [{packet, 2}])
is replaced with:
open_port({spawn, ExtPrg}, [{packet, 2}, binary])
And:
Port ! {self(), {command, encode(Msg)}}, receive {Port, {data, Data}} -> Caller ! {complex, decode(Data)} end
is replaced with:
Port ! {self(), {command, term_to_binary(Msg)}}, receive {Port, {data, Data}} -> Caller ! {complex, binary_to_term(Data)} end
The resulting Erlang program is as follows:
Notice that calling
The following example shows a C program communicating with an Erlang program over a plain port with the Erlang external term format encoding:
The following functions,
Step 1. Compile the C code. This provides the paths to
the include file
unix> gcc -o extprg -I/usr/local/otp/lib/erl_interface-3.9.2/include \ -L/usr/local/otp/lib/erl_interface-3.9.2/lib \ complex.c erl_comm.c ei.c -lei -lpthread
In Erlang/OTP R5B and later versions of OTP, the
In R4B and earlier versions of OTP,
Step 2. Start Erlang and compile the Erlang code:
unix> erl Erlang (BEAM) emulator version 4.9.1.2 Eshell V4.9.1.2 (abort with ^G) 1> c(complex2). {ok,complex2}
Step 3. Run the example:
2> complex2:start("./extprg"). <0.34.0> 3> complex2:foo(3). 4 4> complex2:bar(5). 10 5> complex2:bar(352). 704 6> complex2:stop(). stop