SWIG Features
Having completed a tour of the extension process, let’s zoom in for a closer look at SWIG’s compendium of features. We mentioned earlier that SWIG handles a useful subset of ANSI C/C++, which means support for data structures as well as functions. Specifically, it supports the following:
- Constants and global variables
A C variable can be exported into Perl space as a scalar variable of the same name. SWIG supports the fundamental C data types, enums, and #defined constant values. Variables of complex or user-defined types are automatically mapped to a pair of get/set accessor functions.
- Pointers
Every pointer is treated as a
void
*
by default, regardless of whether it is achar**
orMatrix*
ordouble
***
. This strategy works especially well for user-defined types, because most C libraries don’t expect you to dereference such pointers. For example,fopen
returns aFILE *
, which is simply handed over tofread()
andfwrite()
. In Perl, this pointer is available as a scalar, and Perl doesn’t have to know whether the pointer refers to an array, structure, or a typedef. On the other hand, if you want aVector
*
to a list of integer-valued scalars, you will have to help SWIG out by providing a typemap.- Typemaps
Not every data type is a simple conversion from Perl to C or vice versa. SWIG (like xsubpp) provides a way for you to write arbitrary transformations, such as converting a Perl array to a 10-by-10 matrix. To write a typemap, you need to know Perl’s API for accessing its ...
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.