Begin main content

Adding C to your Perl is easy!

Looking for optimisation options for a client Perl project, I starting thinking about implementing some of the tight loops in C instead of Perl.

There is a CPAN module Inline that makes it easy to inline other languages inside Perl modules (or scripts). With Inline::C you can inline C code, and it will be wrapped, compiled and linked for you (it's only re-compiled if your source changes).

You can call C procedures from Perl, and Inline::C will translate simple scalars for you (int, char *, etc). Or you can use the perl api C macro's to realtively simply access arrays and hashes etc. You do need to increment and decrement the scalar reference counts your self, but if you've been a heavy Perl programmer for a while you probably are used to keeping reference counts in mind.

To whet your appetite, it goes something like this (example simplified from Inline::C-Cookbook

#!/usr/bin/perl

print "SQRT(9^2 + 5^2) = ", pyth(9, 5), "\n";
    
use Inline C => <<'END_C';

double pyth(int x, int y) {
        return sqrt((x * x) + (y * y));
}

END_C

05:00 PM, 12 Aug 2005 by Mark Aufflick Permalink | Short Link

Add comment