通过端口从 Erlang 调用 C 函数的最快、最简单的方法是什么?

ska*_*tek 5 c c++ erlang erlang-ports

Francesco Cesarini 的《Erlang 编程》一书提供了一个很好且易于上手的示例,将 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.
Run Code Online (Sandbox Code Playgroud)

但是,本示例中使用的 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
Run Code Online (Sandbox Code Playgroud)

我尝试使用这个稍微修改过的 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))}),
...
Run Code Online (Sandbox Code Playgroud)

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

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

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

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

Ric*_*rdC 1

首先阅读 Erlang/OTP 在线文档中的互操作性教程:http://erlang.org/doc/tutorial/users_guide.html。当与 C 程序通信时,您只需编写 C 代码从 stdin 读取并写入 stdout,这将连接到 Erlang 端口。您还可以阅读http://manning.com/logan中的第 12 章。