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

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

本文关键字:最简单 方法 是什么 ports 通过 调用 函数 Erlang      更新时间:2023-10-16

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代码使用了electricity库,它为程序员做了所有底层的事情:

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

我试过使用这个稍微修改过的测试。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("%in",x+1);
}

但不幸的是,在测试中接收循环。erl收到消息{#Port<0.2028>,{exit_status,2}}

我的问题是:是否有可能在C/c++中实现类似的东西?是否有现成的库让Erlang通过类似于Ruby的erictricity的端口与C/c++对话?

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

中阅读第12章。

您是否检查过Erl Interface: http://www.erlang.org/doc/tutorial/erl_interface.html ?
我发现的其他有趣的链接如下:

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

我希望这些会有帮助:)