Embedding Perl (Using Perl from C)

You can access a Perl interpreter from C by embedding Perl inside your C program. Since Perl is itself a C program, embedding consists of taking the important chunks of Perl and integrating them into yours.

Note that embedding isn't necessary if your only goal is to use a standalone Perl program and you don't mind launching a separate process to do so. You can use a function like C's popen (3) to exchange data between your C program and any external Perl program, just like you can use Perl's open(PIPE, "| program") or the IPC::Open2 and IPC::Open3 modules to exchange data between your Perl program and any other program. But if you want to avoid the overhead of launching a separate process, you can embed an interpreter into your C program.

When developing long-running applications (say, for embedding in a web server), it's a good idea to maintain a single persistent interpreter rather than creating and destroying interpreters over and over again. The major reason is speed, since Perl will only be loaded into memory once. By using a persistent Perl interpreter, Apache's mod_perl module avoids loading Perl into memory anew every time someone hits an Apache web page. The perlembed manpage provides an example of a persistent interpreter, as well as an example of how a Perl program can manage multiple simultaneous interpreters (another big plus for web servers).

Compiling Embedded Programs

When you embed Perl in C, your C program will usually allocate, ...

Get Programming Perl, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.