Skip to Content
Perl Hacks
book

Perl Hacks

by Chromatic, Damian Conway, Curtis Ovid Poe, Curtis (Ovid) Poe
May 2006
Beginner
298 pages
6h 51m
English
O'Reilly Media, Inc.
Content preview from Perl Hacks

Hack #96. Use Shared Libraries Without XS

Call C code from Perl without needing a compiler.

One of the few ways in which installing Perl modules is painful is when they link to shared libraries written in other languages. The first pain is that someone has to write XS or Inline::C or Swig bindings for the shared library. The second is that installing such modules usually requires a working C development environment—and not every machine nor user has such a luxury.

For simple tasks that merely wrap a shared library, there's no reason you need that much; with a little clever coding you can use just about any shared library written in C with an idea backported from Perl 6 to Perl 5.

The Hack

Consider how Perl passes arguments to functions: in @_, on a stack. As far as the calling conventions work, any function that takes a string, an array reference, and a hash reference looks the same for the purposes of calling the function.

Consider how C passes arguments to functions: much the same way. Any function that takes two integers and returns a double looks the same, again as far as the calling conventions go.

Similarly, any XS code that converts between a Perl function that passes two integers (well, scalars containing integers) to a C function and expects a double (well, a scalar containing a numeric value) is the same. The only difference is the name of the function as Perl sees it and the actual C function it calls. Those are actually very easy to vary.

The P5NCI module builds up ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Perl Debugged

Perl Debugged

Peter Scott, Ed Wright
Perl 6 Deep Dive

Perl 6 Deep Dive

Andrew Shitov
Learning Perl 6

Learning Perl 6

brian d foy
Perl by Example

Perl by Example

Ellie Quigley

Publisher Resources

ISBN: 0596526741Supplemental ContentErrata Page