JavaScript EditorFreeware JavaScript Editor     Perl Tutorials 



Main Page Previous Section Next Section

Recipe 12.19 Writing Extensions in C with Inline::C

12.19.1 Problem

You'd like to write functions in C that you can call from Perl. You may already have tried XS and found it harmful to your mental health.

12.19.2 Solution

Use the Inline::C module available from CPAN:

use Inline C;
$answer = somefunc(20, 4);
print "$answer\n";               # prints 80
_ _END_ _
_ _C_ _
double somefunc(int a, int b) {  /* Inline knows most basic C types */
  double answer = a * b;
  return answer;
}

12.19.3 Discussion

Inline::C was created as an alternative to the XS system for building C extension modules. Rather than jumping through all the hoopla of h2xs and the format of an .xs file, Inline::C lets you embed C code into your Perl program. There are also Inline modules for Python, Ruby, and Java, among other languages.

By default, your C source is in the _ _END_ _ or _ _DATA_ _ section of your program after a _ _C_ _ token. This permits multiple Inlined language blocks in a single file. If you want, use a here document when you load Inline:

use Inline C <<'END_OF_C';
double somefunc(int a, int b) {  /* Inline knows most basic C types */
  double answer = a * b;
  return answer;
}
END_OF_C

Inline::C scans the source code for ANSI-style function definitions. When it finds a function definition it knows how to deal with, it creates a Perl wrapper for the function. Inline can automatically translate the basic C data types (double, int, char *, etc.) by using the typemap that comes with Perl. A typemap shows Perl how to convert between C values and Perl data types, and you can install your own if you need to use more complex data structures than the basic typemap supports.

You can link against external libraries, parse header files as h2xs does, pass and return multiple values, handle objects, and more. See the Inline::C-Cookbook manpage that comes with the Inline::C module for more details.

12.19.4 See Also

The documentation with the Inline::C module from CPAN; the Inline::C-Cookbook manpage

    Main Page Previous Section Next Section
    


    JavaScript EditorJavaScript Verifier     Perl Tutorials


    ©