Erlang驱动
有时我们想在Erlang运行系统中运行foreign-language程序,在这种情况下,程序被编写为共享库,该库动态链接到Erlang运行时系统中。
创建驱动程序
创建链接驱动程序是将foreign-language代码与Erlang连接的最有效方法,但也是最危险的,链接驱动程序中的任何致命错误都将使Erlang系统崩溃。
-module(helloLearnfk). -export([start/0, stop/0]). -export([twice/1, sum/2]). start() -> start("example1_drv" ). start(SharedLib) -> case erl_ddll:load_driver("." , SharedLib) of ok -> ok; {error, already_loaded} -> ok; _ -> exit({error, could_not_load_driver}) end, spawn(fun() -> init(SharedLib) end). init(SharedLib) -> register(example1_lid, self()), Port=open_port({spawn, SharedLib}, []), loop(Port). stop() -> example1_lid ! stop. twice(X) -> call_port({twice, X}). sum(X,Y) -> call_port({sum, X, Y}). call_port(Msg) -> example1_lid ! {call, self(), Msg}, receive {example1_lid, Result} -> Result end. LINKED-IN DRIVERS 223 loop(Port) -> receive {call, Caller, Msg} -> Port ! {self(), {command, encode(Msg)}}, receive {Port, {data, Data}} -> Caller ! {example1_lid, decode(Data)} end, loop(Port); stop -> Port ! {self(), close}, receive {Port, closed} -> exit(normal) end; {'EXIT', Port, Reason} -> io:format("~p ~n" , [Reason]), exit(port_terminated) end. encode({twice, X}) -> [1, X]; encode({sum, X, Y}) -> [2, X, Y]. decode([Int]) -> Int.
祝学习愉快! (发现内容有误?请选中要编辑的内容 -> 右键 -> 修改 -> 提交!帮助我们改进教程质量)
精选教程推荐
👇 以下精选教程可能对您有帮助,拓展您的技术视野
暂无学习笔记,成为第一个分享的人吧!
您的笔记将帮助成千上万的学习者