从Erlang通过ports调用C函数的最快和最简单的方法是什么?
What is the fastest and easiest way to call a C function from Erlang via ports?
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.
您是否检查过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
我希望这些会有帮助:)
- 当无法使用模板和宏时,生成类型变体C++代码的最简单方法是什么?
- 在OSX上使用CMake将Adobe的XMP工具包构建为共享库的最简单方法是什么?
- 通过比较C++中的行在 txt 文件中搜索的最简单方法是什么?
- 将时间戳打印到流的最简单方法
- 在C++中创建文件夹选取器对话框的最简单方法是什么?
- boost::variant - 对变体应用算术的最简单方法
- 创建可以遍历 std::map 值的通用模板迭代器的最简单方法是什么?
- 在C++中将算术类型转换为 std::array 的最简单方法<uint8_t>
- C++-将ASCII字符数组中可能的数值转换为字符的最简单方法
- 从 txt 文件中读取数据的最简单方法
- 根据浮点符号对浮点进行舍入的最简单方法是什么
- 对于我扩展此程序来计算最高10x10矩阵的倒数的最简单方法是什么
- C++98 中获取并继续调用当前类不知道的类方法的最简单方法是什么?
- 编写要在 Python 中使用的并行 C/C++ 模块的最简单方法
- 开放式颜色多边形表面的最简单方法
- 确定代码中当前程序集是否为 32/64 位的最简单方法
- 将unique_ptr存储在堆上的最简单方法是什么
- 使用 C# 获取 OpenGL 版本的最简单方法
- 在自定义 C/C++ 程序中获取 PPP0 接口 Tx/Rx 字节的最简单方法是什么?
- 为depth_first_search定义颜色图的最简单方法