SWIG Perl Examples – How to Interface Perl to C Using SWIG

SWIG is used to simplify the task of interfacing different languages to C and C++ programs.

For our discussion, in this article we will explain how to use SWIG to interface from Perl to C programs.
Some may think, why would one write Perl programs and call a C function from it? The answer to this lies in the strength of C/C++ programs, which is performance. A developer may choose to code in Perl/Python, because it is lot easier to design GUI using these languages and also the language itself takes care of memory allocation/de-allocation.

So, lets review the basics of SWIG. First we need to write a C program, which we want to access it from Perl. Then we need to write an ‘interface’ file for the C program.

Step 1: Creating the C program

area.c

Step 2: Creating the Interface File

Interface file are the one which is used by SWIG to provide wrapper files. The basic interface file should include all the prototypes of the function and variables. Each interface file will have a ‘module’ directive and ‘module name’ followed by it. Interface files are created with ‘.i’ extension.

Now when we run this Perl program, it uses the ‘area.pm’ file (use area;), which loads the shared object file using ‘DynaLoader’, and calls the C program.

You can also say a variable in C is readonly by using ‘%immutable;’ directive, so that from Perl you can’t modify the variable. In our previous example, the variable ‘$area::pi’ can be changed, which in-turn affects the ‘area_of_circle’ function, which uses the ‘pi’ variable for calculation. The interface file will look like,

About The Geek Stuff

My name is Ramesh Natarajan. I will be posting instruction guides, how-to, troubleshooting tips and tricks on Linux, database, hardware, security and web. My focus is to write articles that will either teach you or help you resolve a problem. Read more about Ramesh Natarajan and the blog.

Contact Us

Email Me :
Use this Contact Form to get in touch me with your comments, questions or suggestions about this site. You can also simply drop me a line to say hello!.