繁体   English   中英

如何编译加载到字符串中的erlang代码?

[英]How to compile erlang code loaded into a string?

我有一个生成的字符串,其中包含erlang模块的代码。

有没有办法直接从字符串编译生成的模块?

或者有没有办法将字符串转换为compile:forms/1所需的格式?

或者我是否必须先将其保存到临时文件中,然后使用compile:file/1进行compile:file/1

或者,我可以添加对编译模块的支持,但必须有一个原因,为什么编写erlang的好人没有添加它。

您需要将字符串扫描到标记中,然后将标记解析为表单。 不幸的是,它一次只能解析一个表单,因此您需要在表单边界处剪切字符串或标记。 这是一个简短的例子:

% create tokens from strings containing forms
> {ok, MTs, _} = erl_scan:string("-module(z).").
> {ok, ETs, _} = erl_scan:string("-export([f/0]).").
> {ok, FTs, _} = erl_scan:string("f() -> hello_world.").
% tokens to erl_parse trees
> {ok,MF} = erl_parse:parse_form(MTs).
> {ok,EF} = erl_parse:parse_form(ETs).
> {ok,FF} = erl_parse:parse_form(FTs).

% compile forms to binary
> {ok, z, Bin} = compile:forms([MF,EF,FF]).
{ok,z,<<70,79,82,49,0,0,1,164,66,69,65,77,65,116,111,109,0,0,0,...>>}

% load module from binary
> code:load_binary(z, "nofile", Bin).
{module,z}

% test
> z:f().
hello_world

或者,您可以扫描字符串,然后在{dot, _}标记处分割生成的标记列表。

将字符串的内容存储在具有模块名称的文件中(如果代码中没有),并使用编译模块进行编译
代码在VM中可用。 我正在使用此技术将配置文件转换为模块。 这样在执行期间没有太多的二进制副本。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM