Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I link a static C object file to Perl?

I have a function written in C (Say in HelloWorld.c file). I want to compile this and need to create a staic object file HelloWorld.a

Finally I need to call this from a Perl program (HelloWorld.pl).

like image 643
Pramodh Avatar asked Sep 28 '10 07:09

Pramodh


2 Answers

To call from perl to C one usually compiles a shared, not a static, library from his c code, and then loads that into the perl interpreter using the XSLoader or DynaLoader module.

To then be able to call the C code from perl space there's many ways. The most common one is writing something called XSUBs, which have a perl-side interface, map the perl calling-conventions to C calling-conventions, and call the C functions. Those XSUBs are usually also linked into the shared library that'll be loaded into perl, and written in a language called XS, which is extensively documented in perlxs and perlxstut.

There's also other ways to build that wrapper layer, like various XS code generators, as well as SWIG. But you could also call to the C functions directly using an NCI. Perl also has many of those. The P5NCI is one example of those, the ctypes module developed in this year's Google Summer of Code program is another.

Another related technique that should probably be mentioned here is Inline::C, and the other modules of the Inline family. They allow you to write code in other languages directly in perl, and call to it. Under the hood Inline::C just builds XS code and loads the result of that into the interpreter.

like image 134
rafl Avatar answered Sep 25 '22 21:09

rafl


As @rafl says, you should use a shared library.

If you must use a static library, then you have to rebuild Perl with the static library built in. You'll need some XS glue too. However, this is messy enough that you really, really don't want to do it.

like image 26
Jonathan Leffler Avatar answered Sep 24 '22 21:09

Jonathan Leffler