text: - NAME
  - DESCRIPTION
  - PREAMBLE
  - ROADMAP
  - Compiling your C program
  -
  - MORAL
  - AUTHOR
  NAME
  perlembed - how to embed perl in your C program
  DESCRIPTION
  PREAMBLE
  Do you want to:
  - Use C from Perl?
  Read perlcall and perlxs.
  - Use a Unix program from Perl?
  Read about back-quotes and about
  systemand
  exec"
  There's one example in each of the nine sections:
  "
  Compiling your C program
  If you have trouble compiling the scripts in this documentation, you're not alone. The cardinal rule: COMPILE THE PROGRAMS copying the lib directory.)
  When you use Perl from C, your C program will--usually--allocate, "run", and deallocate a PerlInterpreter object, which is defined by the perl library.
  If your copy of Perl is recent enough to contain this documentation  5.003_05, the incantation is a bit different:
  % followingding Perl (the language), so I'll demonstrate embedding with miniperlmain.c, from the source distribution. Here's a bastardized, nonportable version of miniperlmain.c containing the essentials of embedding:
  #include <EXTERN.h> /* from the Perl distribution */ #include <perl.h> /* from the Perl distribution */ static PerlInterpreter *my_perl; /*** The Perl interpreter ***/ int main(int argc, char **argv, char **env) { my_perl = perl_alloc(); perl_construct(my_perl); perl_parse(my_perl, NULL, argc, argv, (char **)NULL); perl_run(my_perl); perl_destruct(my_perl); perl_free(my_perl); }
  Notice that we don't use the
  env pointer. Normally handed to
  perl_parse as its final argument,
  env here is replaced by
  NULL, which means that the current environment will be used.().
  Calling a Perl subroutine from your C program
  To call individual Perl subroutines, you can use any of the perl_call_* functions documented in the perlcall manpage. In this example we'll use perl_call_argv.
  That's shown below, in a program I'll call showtime.c.
  #include <EXTERN.h> #include <perl.h> static PerlInterpreter *my_perl; int main(int argc, char **argv, char **env) { char *args[] = { NULL }; my_perl = perl_alloc(); perl_construct(my_perl); perl_parse(my_perl, NULL, argc, argv, NULL); /*** skipping perl_run() ***/ perl_call_argv("showtime", G_DISCARD | G_NOARGS, args); perl_destruct(my_perl); perl_free(my_perl); }
  yielding the number of seconds that elapsed between January 1, 1970 (the beginning of the Unix epoch), and the moment I began writing this sentence.
  In this particular case we don't have to call perl_run, but in general it's considered good practice to ensure proper initialization of library code, including execution of all object
  DESTROY methods and package
  END {} blocks.
  If you want to pass arguments to the Perl subroutine, you can add strings to the
  NULL-terminated
  args list passed to perl_call_argv. For other data types, or to examine return values, you'll need to manipulate the Perl stack. That's demonstrated in the last section of this document: "Fiddling with the Perl stack from your C program".
  Evaluating a Perl statement from your C program
  Perl provides two API functions to evaluate pieces of Perl code. These are "perl_eval_sv()" in perlguts and "perl_eval_pv()" in perlguts.
  Arguably, these are the only routines you'll ever need to execute snippets of Perl code from within your C program. Your code can be as long as you wish; it can contain multiple statements; it can employ "use" in perlfunc, "require" in perlfunc and "do" in perlfunc to include external Perl files.
  perl) { char *embedding[] = { "", "-e", "0" }; my_perl = perl_alloc(); perl_construct( my_perl ); perl_parse(my_perl, NULL, 3, embedding, NULL); perl_run(my_perl); /** Treat $a as an integer **/ perl_eval_pv("$a = 3; $a **= 2", TRUE); printf("a = %d\n", SvIV(perl_get_sv("a", FALSE))); /** Treat $a as a float **/ perl_eval_pv("$a = 3.14; $a **= 2", TRUE); printf("a = %f\n", SvNV(perl_get_sv("a", FALSE))); /** Treat $a as a string **/ perl_eval_pv("$a = 'rekcaH lreP rehtonA tsuJ'; $a = reverse($a);", TRUE); printf("a = %s\n", SvPV(perl_get_sv("a", FALSE), na)); perl_destruct(my_perl); perl_free(my_perl); }
  All of those strange functions with sv in their names help convert Perl scalars to C types. They're described in perlguts. expression. It is also possible and in most cases a better strategy to fetch the return value from perl_eval_pv instead. Example:
  ... SV *val = perl_eval_pv("reverse 'rekcaH lreP rehtonA tsuJ'", TRUE); printf("%s\n", SvPV(val,na)); ...
  This way, we avoid namespace pollution by not creating global variables and we've simplified our code as well.
  Performing Perl pattern matches and substitutions from your C program
  The perl_eval_sv() function lets us evaluate chunks of Perl code, so we can define some functions that use it to "specialize" in matches and substitutions: match(), substitute(), and matches().
  char
  AV at according to the operation, returning the number of substitutions made.
  int matches(SV *string, char *pattern, AV **matches);
  Given an
  SV, a pattern, and a pointer to an empty
  AV, matches() evaluates
  $string =~ $pattern in an array context, and fills in matches with the array elements, returning the number of matches found.
  Here's a sample program, match.c, that uses all three (long lines have been wrapped here):
  #include <EXTERN.h> #include <perl.h> /** my_perl_eval_sv(code, error_check) ** kinda like perl_eval_sv(), ** but we pop the return value off the stack **/ SV* my_perl_eval_sv(SV *sv, I32 croak_on_error) { dSP; SV* retval; PUSHMARK(sp); perl_eval_sv(sv, G_SCALAR); SPAGAIN; retval = POPs; PUTBACK; if (croak_on_error && SvTRUE(GvSV(errgv))) croak(SvPVx(GvSV(errgv), na)); return retval; } /** match(string, pattern) ** ** Used for matches in a scalar context. ** ** Returns 1 if the match was successful; 0 otherwise. **/ I32 match(SV *string, char *pattern) { SV *command = newSV(0), *retval; sv_setpvf(command, "my $string = '%s'; $string =~ %s", SvPV(string,na), pattern); retval = my_perl(0), *retval; sv_setpvf(command, "$string = '%s'; ($string =~ %s)", SvPV(*string,na), pattern); retval = my_perl_eval_sv(command, TRUE); SvREFCNT_dec(command); *string = perl_get_sv("string", FALSE); return SvIV(retval); } /** matches(string, pattern, matches) ** ** Used for matches in an array context. ** ** Returns the number of matches, ** and fills in **matches with the matching substrings **/ I32 matches(SV *string, char *pattern, AV **match_list) { SV *command = newSV(0); I32 num_matches; sv_setpvf(command, "my $string = '%s'; @array = ($string =~ %s)", SvPV(string,na), pattern); my_perl_eval_sv(command, TRUE); SvREFCNT_dec(command); *match_list = perl_get_av("array", FALSE); num_matches = av_len(*match_list) + 1; /** assume $[ is 0 **/ return num_matches; } main (int argc, char **argv, char **env) { PerlInterpreter *my_perl = perl_alloc(); char *embedding[] = { "", "-e", "0" }; AV *match_list; I32 num_matches, i; SV *text = newSV(0); perl_construct(my_perl); perl_parse(my_perl, NULL, 3, embedding, NULL);),na)); printf("\n"); /** Remove all vowels from text **/ num_matches = substitute(&text, "s/[aeiou]//gi"); if (num_matches) { printf("substitute: s/[aeiou]//gi...%d substitutions made.\n", num_matches); printf("Now text is: %s\n\n", SvPV(text,na)); } /** Attempt a substitution **/ if (!substitute(&text, "s/Perl/C/")) { printf("substitute: s/Perl/C...No substitution made.\n\n"); } SvREFCNT_dec(text); perl_destruct_level = 1; perl_destruct(my_perl); perl_free(my_perl); } substitute: s/Perl/C...No substitution made.
  Fiddling with the Perl stack from your C program
  When trying to explain stacks, most computer science textbooks.
  Then you'll need to know how to manipulate the Perl stack. That's described in perlcall.
  Once you've understood those, embedding Perl in C is easy.
  Because C has no builtin function for integer exponentiation, let's make Perl's ** operator available to it (this is less useful than it sounds, because Perl implements ** with C's pow() function). First I'll create a stub exponentiation function in power.pl:
  sub expo { my ($a, $b) = @_; return $a ** $b; }
  Now I'll create a C program, power.c, with a function PerlPower() that contains all the perlguts necessary to push the two arguments into expo() and to pop the return value out. Take a deep breath...
  #include <EXTERN.h> #include <perl.h> static PerlInterpreter *my_perl; */ perl" }; my_perl = perl_alloc(); perl_construct( my_perl ); perl_parse(my_perl, NULL, 2, my_argv, (char **)NULL); perl_run(my_perl); PerlPower(3, 4); /*** Compute 3 ** 4 ***/ perl_destruct(my_perl); perl_free(my_perl); } occasionally "perl_call_argv" in perlcall,OADed subroutines; use vars '%Cache'; sub valid_package_name { my($string) = @_; $string =~ s/([^A-Za-z0-9\/])/sprintf("_%2x",unpack("C",$1))/eg; # second pass only for words starting with a digit $string =~ s|/(\d)|sprintf("/_%2x",unpack("C",$1))|eg; # Dress it up as a real package name $string =~ s|/|::|g; return "Embed" . $string; } #borrowed from Safe.pm sub delete_package { my $pkg = shift; my ($stem, $leaf); no strict 'refs'; $pkg = "main::$pkg\::"; # expand to full symbol table name ($stem, $leaf) = $pkg =~ m/(.*::)(\w+::)$/; my $stem_symtab = *{$stem}{HASH}; delete $stem_symtab->{$leaf}; }__ /* persistent.c */ #include <EXTERN.h> #include <perl.h> /* 1 = clean out filename's symbol table after each request, 0 = don't */ #ifndef DO_CLEAN #define DO_CLEAN 0 #endif static PerlInterpreter *perl = NULL; int main(int argc, char **argv, char **env) { char *embedding[] = { "", "persistent.pl" }; char *args[] = { "", DO_CLEAN, NULL }; char filename [1024]; int exitstatus = 0; if((perl = perl_alloc()) == NULL) { fprintf(stderr, "no memory!"); exit(1); } perl_construct(perl); exitstatus = perl_parse(perl, NULL, 2, embedding, NULL); if(!exitstatus) { exitstatus = perl_run(perl); while(printf("Enter file name: ") && gets(filename)) { /* call the subroutine, passing it the filename as an argument */ args[0] = filename; perl_call_argv("Embed::Persistent::eval_file", G_DISCARD | G_EVAL, args); /* check $@ */ if(SvTRUE(GvSV(errgv))) fprintf(stderr, "eval error: %s\n", SvPV(GvSV(errgv),na)); } } perl_destruct_level = 0; perl_destruct(perl); perl_free(perl); exit(exitstatus); }
  Now compile:
  % cc -o persistent persistent.c `perl -MExtUtils::Embed -e ccopts -e ldopts`
  Here's a example script file:
  #test.pl my $string = "hello"; foo($string); sub foo { print "foo says: @_\n"; }
  Now run:
  % persistent Enter file name: test.pl foo says: hello Enter file name: test.pl already compiled Embed::test_2epl->handler foo says: hello Enter file name: ^C, the global variable
  perl_destruct_level is set to
  0, since extra cleaning isn't needed when a program has only one interpreter.
  Setting
  perl_destruct_level to
  1 makes everything squeaky clean:
  perl_destruct_level = 1; while(1) { ... /* reset global variables here with perl_destruct_level = 1 */ perl_construct(my_perl); ... /* clean and reset _everything_ during perl_destruct */ perl_destruct(my_perl); perl_free(my_perl); ... /* let's go do it again! */ }
  When perl_destruct() is called, the interpreter's syntax parse tree and symbol tables are cleaned up, and global variables are reset.
  Now suppose we have more than one interpreter instance running at the same time. This is feasible, but only if you used the
  -DMULTIPLICITY flag when building Perl. By default, that sets
  perl_destruct_level to
  1.
  Let's give it a try:
  #include <EXTERN.h> #include <perl.h> /* we're going to embed two interpreters */ /* we're going to embed two interpreters */ #define SAY_HELLO "-e", "print qq(Hi, I'm $^X\n)" int main(int argc, char **argv, char **env) { PerlInterpreter *one_perl = perl_alloc(), *two_perl = perl_alloc(); char *one_args[] = { "one_perl", SAY_HELLO }; char *two_args[] = { "two_perl", SAY_HELLO }; perl_construct(one_perl); perl_construct(two_perl); perl_parse(one_perl, NULL, 3, one_args, (char **)NULL); perl_parse(two_perl, NULL, 3, two_args, (char **)NULL); perl_run(one_perl); perl_run(two_perl); perl_destruct(one_perl); perl_destruct(two_perl); perl_free(one_perl); perl_free(two_perl); }:
  #ifdef __cplusplus # define EXTERN_C extern "C" #else # define EXTERN_C extern #endif static void xs_init _((void)); EXTERN_C void boot_DynaLoader _((CV* cv)); EXTERN_C void boot_Socket _((CV* cv)); EXTERN_C void xs_init() { char *file = __FILE__; /* DynaLoader is a special case */ newXS("DynaLoader::boot_DynaLoader", boot_DynaLoader, file); newXS("Socket::bootstrap", boot_Socket, file); }
  Simply put: for each extension linked with your Perl executable (determined during its initial configuration on your computer or when adding a new extension), a Perl subroutine is created to incorporate the extension's routines. Normally, and perlguts for more details.
  Embedding Perl under Win32
  At the time of this writing, there are two versions of Perl which run under Win32. Interfacing to Activeware's Perl library is quite different from the examples in this documentation, as significant changes were made to the internal Perl API. However, it is possible to embed Activeware's Perl runtime, see the Perl for Win32 FAQ:
  With the "official" Perl version 5.004 or higher, all the examples within this documentation will compile and run untouched, although, the build process is slightly different between Unix and Win32.
  For starters, backticks don't work under the Win32 native command shell! The ExtUtils::Embed kit on CPAN ships with a script called genmake, which generates a simple makefile to build a program from a single C source file. It can be used like so:
  C:\ExtUtils-Embed\eg> perl genmake interp.c C:\ExtUtils-Embed\eg> nmake C:\ExtUtils-Embed\eg> interp -e "print qq{I'm embedded in Win32!\n}"
  You may wish to use a more robust environment such as the MS Developer stdio. In this case, to generate perlxsi.c run:
  perl -MExtUtils::Embed -e xsinit
  Create a new project,. Finnally, select Build -> Build interp.exe and you're ready to go!
  MORAL
  You can sometimes write faster code in C, but you can always write code faster in Perl. Because you can use each from the other, combine them as you wish.
  AUTHOR
  Jon Orwant and <orwant@tpj.com> and Doug MacEachern <dougm@osf.org>, with small contributions from Tim Bunce, Tom Christiansen, Hallvard Furuseth, Dov Grobgeld, and Ilya Zakharevich.
  Check out Doug's article on embedding in Volume 1, Issue 4 of The Perl Journal. Info about TPJ is available from.
  July 17, 1997
  Some of this material is excerpted from Jon Orwant's book: Perl 5 Interactive, Waite Group Press, 1996 (ISBN 1-57169-064-6) and appears courtesy of Waite Group Press.
  Copyright (C) 1995, 1996, 1997 Doug MacEachern and Jon Orwant. All Rights Reserved.
  Although destined for release with the standard Perl distribution, this document is not public domain, nor is any of Perl and its.