Adding Extensions

In the preceding pages, we created C applications that made calls to the Perl library, parsed scripts, and sent data between Perl and C space. In the meantime, we studiously avoided the issue of extensions, if you recall, by passing NULL to perl_parse instead of the address of an initialization subroutine. This means that we could not make use of any C-based extensions in the scripts, even common ones such as Socket and SDBM — clearly an unacceptable solution for real applications.

In this section, we learn a simple way of making standard and custom extensions accessible to the embedded Perl interpreter.

The initialization subroutine, which we will refer to as xs_init, is responsible for calling the initialization routines for all statically linked extensions. If you prefer dynamic loading, xs_init simply needs to initialize the built-in dynamic loader.

Instead of handcoding xs_init, we rely on a very convenient module called ExtUtils::Embed to produce it for us. This module is packaged with the Perl distribution, and is used like this:

perl -MExtUtils::Embed -e xsinit -- -o xsinit.c -std IO::Socket DBI

The -M option is identical to saying "use ExtUtils::Embed;“. This invocation produces a file called xsinit.c with a publicly available function called xs_init, which in turn contains the code to initialize all the standard modules (thanks to the -std argument), and the two custom modules, IO::Socket and DBI.

How does this module know what is standard or whether we ...

Get Advanced Perl Programming 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.