4

Francesco Cesarini 的“Erlang Programming”一书提供了一个很好且易于上手的将 Erlang 连接到 Ruby 的示例(通过端口实现):

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.

但是,本例中使用的 Ruby 代码使用 Erlictricity 库,它为程序员完成了所有低级的事情:

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

我尝试使用这个稍作修改的 test.erl 代码:

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))}),
...

说一个非常简单的 C 文件:

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

但不幸的是 test.erl 中的接收循环收到一条消息{#Port<0.2028>,{exit_status,2}}

我的问题是:是否可以在 C/C++ 中实现类似的东西?是否有任何现成的 Erlang 库可以通过类似于 Erlictricity for Ruby 的端口与 C/C++ 对话?

4

2 回答 2

1

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.

于 2011-10-13T07:46:36.517 回答
0

Have you checked out Erl Interface here: http://www.erlang.org/doc/tutorial/erl_interface.html ?
Other interesting links i have found are listed below:

http://www.erlang.org/documentation/doc-4.9.1/pdf/erl_interface-3.2.pdf
http://www.erlang.org/doc/apps/erl_interface/index.html
http://dukesoferl.blogspot.com/2010/01/minor-erlang-interface-tricks.html

I hope those will help :)

于 2011-10-08T09:08:51.537 回答