This is an example of how to solve the 
The example below shows an Erlang program communicating with a C program over a plain port with home made encoding.
Compared to the Erlang module 
      above used for the plain port, there are two differences when using Erl_Interface on the C side: Since Erl_Interface operates on the Erlang external term format the port must be set to use binaries and, instead of inventing an encoding/decoding scheme, the BIFs 
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 shown below.
Note that calling 
The example below shows a C program communicating with an Erlang program over a plain port with home made encoding.
Compared to the C program above
      used for the plain port the 
erl_init(NULL, 0);
For reading from and writing to the port the functions 
The function 
int main() {
  ETERM *tuplep;
  while (read_cmd(buf) > 0) {
    tuplep = erl_decode(buf);
    In this case 
    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));
    Last, 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 shown below:
1. Compile the C code, providing 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 R5B and later versions of OTP, the 
      In R4B and earlier versions of OTP, 
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}
    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