c++cerlangerlang-ports

What is the fastest and easiest way to call a C function from Erlang via ports?


Francesco Cesarini's "Erlang Programming" book provides a nice and simple-to-start-with example of connecting Erlang to Ruby (implemented through ports):

module(test.erl).
compile(export_all).    

test() ->
    Cmd = "ruby echoFac.rb",
    Port = open_port({spawn, Cmd}, [{packet, 4}, use_stdio, exit_status, binary]),
    Payload = term_to_binary({fac, list_to_binary(integer_to_list(23))}),
    port_command(Port, Payload),
    receive
     {Port, {data, Data}} ->
      {result, Text} = binary_to_term(Data),
      Blah = binary_to_list(Text),
      io:format("~p~n", [Blah])
    end.

However, the Ruby code used in this example uses the Erlictricity library, which does all the low-level things for the programmer:

require 'rubygems'
require 'erlectricity'
require 'stringio'
def fac n
if (n<=0) then 1 else n*(fac (n-1)) end
end
receive do |f|
f.when(:fac, String) do |text|
n = text.to_i
f.send!(:result, "#{n}!=#{(fac n)}")
f.receive_loop
end
end

I have tried to use this slightly modified test.erl code:

test(Param) ->
        Cmd = "./add",
        Port = open_port({spawn, Cmd}, [{packet, 4}, use_stdio, exit_status, binary]),
        Payload = term_to_binary({main, list_to_binary(integer_to_list(Param))}),
...

to speak with a very simple C file:

/* add.c */
#include <stdio.h>
int main(int x) {
 // return x+1;
 printf("%i\n",x+1);
}

But unfortunately the receive loop in test.erl gets a message {#Port<0.2028>,{exit_status,2}}

My question is: is it possible to implement anything similar in C/C++? Are there any ready-made libraries for Erlang to talk with C/C++ via ports similar to Erlictricity for Ruby?


Solution

  • Start by reading the Interoperability Tutorial in the Erlang/OTP online documentation: http://erlang.org/doc/tutorial/users_guide.html. When communicating with a C program, you just write the C code to read from stdin and write to stdout, and this will be hooked up to the Erlang port. You could also read chapter 12 in http://manning.com/logan.