[erlang-questions] Loading code generated on the fly

Edwin Fine erlang-questions_efine@REDACTED
Sat Sep 27 21:06:12 CEST 2008


This is what I have been using successfully for a short while now. Hope this
helps.

%%
%% Compile from string hack by Mats Cronqvist (Thank You!!)
%% NOTE: Does not work if there are macros in Text!
%%
compile_and_load(Text) ->
    try
        Forms = ?MODULE:scan_and_parse(Text, 1, []),
        {ok, Mod, Bin} = compile:forms(Forms),
        {module, _M} = code:load_binary(Mod, "generated", Bin),
        io:format(
            "~p:compile_and_load replaced module ~p with [~s]~n",
            [?MODULE, Mod, Text]
        ),
        code:purge(Mod),
        ok
    catch
        Err:Reason ->
            io:format(
                "compile_and_load failed, err:reason {~p:~p}~n~p~n",
                [Err, Reason, Text]
            ),
            {Err, Reason}
    end.

scan_and_parse([], _Line, Forms) ->
    lists:reverse(Forms);
scan_and_parse(Text, Line, Forms) ->
    {done, {ok, Toks, NLine}, Cont} = erl_scan:tokens([], Text, Line),
    {ok, Form} = erl_parse:parse_form(Toks),
    ?MODULE:scan_and_parse(Cont, NLine, [Form|Forms]).



2008/9/27 Robert Virding <rvirding@REDACTED>

> I am generating compiled erlang code on the fly without saving using files
> (using LFE) and need to load the compiled binary into the system. Now, I
> know how to do myself "by hand" but I would prefer to go through the normal
> code loader to keep it all clean.
>
> There is a call code:load_binary(Module, FileName, Binary) which seems to
> do what I want, BUT there is this argument FileName. Now I don't intend to
> save the module in a file unless I really have to as it seems like a bit of
> unnecessary work to save it in a file just so I can load it. What is the
> significance of the FileName argument and does it matter what I set it to?
> Can I just call Module.beam and be done with?
>
> Robert
>
>
> _______________________________________________
> erlang-questions mailing list
> erlang-questions@REDACTED
> http://www.erlang.org/mailman/listinfo/erlang-questions
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20080927/2fd64b1e/attachment.htm>


More information about the erlang-questions mailing list