Degrees of Freedom

Before we conclude the essential part of this chapter, let us quickly recap all the places where you can plug in code to help XS and SWIG produce a smooth interface (for the script programmer):

Perl module

So far, the Perl module produced by these tools has been used only to bootstrap the C code, but there’s no reason why it shouldn’t have some custom subroutines too. The XS example presented earlier, in the “Modifying Parameters” section, could easily have been implemented in Perl space.

Typemaps

Supply snippets of code to convert between Perl and C data types.

Wrapper code in the interface files

The CODE and PPCODE directives allow you to insert a variety of custom translation tasks. In SWIG, you can inline custom C code as follows:

%module FunMath
%inline %{
int factorial(int n){return (n == 1) ? 1 : n *(n -1)};
%}

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.