Embedding Perl in C++

In addition to all visual features I want, I also want the framework/simulator to be easily configurable and scriptable, and what language provides better parsing and scripting capabilities than Perl? (or Python, or Ruby, but my experience with those is very limited...)

It's (non)surprisingly easy to call perl from C as the following code shows:

#ifdef __cplusplus
  extern "C" {
#   include <EXTERN.h>
#   include <perl.h>
    static PerlInterpreter *my_perl;

int main(int argc, char **argv, char **env) {

  my_perl = perl_alloc();

  perl_parse(my_perl, NULL, argc, argv, env);


  return 0;

This code can be compiled with something like this:

g++ -c interp.c -o interp.o `perl -MExtUtils::Embed -e ccopts`
g++ interp.o -o interp `perl -MExtUtils::Embed -e ldopts`

and then interp -v should give you the same output as perl -v.

While it may be easy to compile and run this simple program, it's still a challenge to pass complex data structures between C and Perl as you need to know all those *_sv, *_pv, *_av and stack manipulation calls. Fortunately for me I own a copy of Extending and Embedding Perl. There are even libraries like PerlStream that will hide all that complexity from you.

Another problem is that it means having additional libraries and module files (if you happen to use Perl modules) in your distribution. On Windows this can be solved by using Thinstall, PEBundle, or one of many other exe packers that compress executable and dll files into a single file.

Leave a comment

what will you say?