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 home made encoding:
Compared to the C program in
erl_init(NULL, 0);
The following functions,
The function
int main() { ETERM *tuplep; while (read_cmd(buf) > 0) { tuplep = erl_decode(buf);
Here,
fnp = erl_element(1, tuplep); argp = erl_element(2, tuplep);
The macros
if (strncmp(ERL_ATOM_PTR(fnp), "foo", 3) == 0) { res = foo(ERL_INT_VALUE(argp)); } else if (strncmp(ERL_ATOM_PTR(fnp), "bar", 3) == 0) { res = bar(ERL_INT_VALUE(argp)); }
Now an
intp = erl_mk_int(res);
The resulting
erl_encode(intp, buf); write_cmd(buf, erl_eterm_len(intp));
Finally, the memory allocated by the
erl_free_compound(tuplep); erl_free_term(fnp); erl_free_term(argp); erl_free_term(intp);
The resulting C program is as follows:
Step 1. Compile the C code. This provides the paths to
the include files
unix> gcc -o extprg -I/usr/local/otp/lib/erl_interface-3.2.1/include \\ -L/usr/local/otp/lib/erl_interface-3.2.1/lib \\ complex.c erl_comm.c ei.c -lerl_interface -lei
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