in reply to Re^2: Extending an embedded Perl interpreter without a .pm file
in thread Extending an embedded Perl interpreter without a .pm file

One clarification, I did the eval_pv() thing using one big string that contained the entire contents of the .pm file that I was trying to get rid of. That didn't work so I next did it as series of eval_pv() calls, one per line of the .pm file. That didn't work, either. Both cases the results were as described above.
  • Comment on Re^3: Extending an embedded Perl interpreter without a .pm file

Replies are listed 'Best First'.
Re: Extending an embedded Perl interpreter without a .pm file
by benizi (Hermit) on Feb 08, 2005 at 22:27 UTC

    How about eval_pv'ing a string containing the contents of the file, plus "DynTrans->import;"? use DynTrans; is roughly equivalent to BEGIN { require DynTrans; DynTrans->import; }. eval_pv'ing the contents of DynTrans.pm is like require-ing it. Add a "package main;", before the import, and voila!

    Tested this, and it works:

    Key lines:

    /* moduletext = text of module + "package main; DynTrans->import;" */ eval_pv(moduletext, TRUE); /* ~ use DynTrans; */ eval_pv("$a = fortytwo();", TRUE); /* its function is available */

    Full C source

    #include <EXTERN.h> #include <perl.h> static PerlInterpreter *pi; /* Note the last two lines "package main; DynTrans->import" */ static char *moduletext = "package DynTrans;\n\ use base qw/Exporter/;\n\ our @EXPORT;\n\ BEGIN { @EXPORT = qw/&fortytwo/; }\n\ sub fortytwo { 42; }\n\ 1;\n\ package main;\n\ DynTrans->import;"; int main(int argc, char **argv, char **env) { STRLEN n_a; char *embedding[] = { "", "-e", "0" }; pi = perl_alloc(); perl_construct(pi); perl_parse(pi, NULL, 3, embedding, NULL); PL_exit_flags |= PERL_EXIT_DESTRUCT_END; perl_run(pi); eval_pv(moduletext, TRUE); /* ~ use DynTrans; */ eval_pv("$a = fortytwo();", TRUE); /* its function is available */ printf("EXPECT: a = 42\nGOT: a = %d\n", SvIV(get_sv("a", FALSE) +)); perl_destruct(pi); perl_free(pi); return 0; }
    OUTPUT: EXPECT: a = 42 GOT: a = 42