您的位置:首页 > 其它

【Erlang新手成长日记】Erlang端口与外部C程序交互

2012-09-01 15:05 253 查看
参考文档:

  《Programming Erlang》,第12章:Interfacing Techniques

创建C源文件:

  hello.c 具体函数的实现

hello.erl

-module(hello).

-export([start/0, stop/0]).
-export([twice/1, sum/2]).

-define(PORTNAME, ?MODULE).

start() ->
Fun = fun() ->
register(?PORTNAME, self()),
process_flag(trap_exit, true),
Port = open_port({spawn, "./hello"}, [{packet, 2}]),
loop(Port)
end,
spawn(Fun).

stop() ->
?PORTNAME ! stop.

twice(X) -> call_port({twice, X}).
sum(X, Y) -> call_port({sum, X, Y}).

call_port(Message) ->
?PORTNAME ! {call, self(), Message},
receive
{?PORTNAME, Result} ->
Result
end.

loop(Port) ->
receive
{call, Caller, Message} ->
Port ! {self(), {command, encode(Message)}},
receive
{Port, {data, Data}} ->
Caller ! {?PORTNAME, decode(Data)}
end,
loop(Port);
stop ->
Port ! {self(), close},
receive
{Port, closed} ->
exit(normal)
end;
{'EXIT', Port, Reason} ->
exit({port_terminated, Reason})
end.

encode({twice, X}) ->
[1, X];
encode({sum, X, Y}) ->
[2, X, Y].

decode([Int]) ->
Int.


编译C源文件,生成可执行文件

gcc -o hello hello.c hello_driver.c erl_communication.c


编译Erlang源文件,生成.beam文件

erlc hello.erl
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: