Compiling C DLLs and using them from Perl  Hot PDF Print E-mail
Tag it:
Delicious
Furl it!
Digg
NewsVine
Reddit
YahooMyWeb
Technorati
Articles Reviews Perl
Written by Adi Bach   
Thursday, 15 February 2007

A few months ago I managed to control a National Instruments Digital IO card (sitting in a PCI slot in my PC) from Perl. I accomplished this by installing the Win32::API module, and loading the card’s .dll API. I had a few struggles with Win32::API as some things weren’t obvious, but after some searching and good advice from Perlmonks, it worked.


Today I had another encounter with Win32::API. I have some C code I want to access from Perl. So, I compiled it in Visual C++ into a DLL, but Win32::API kept segfaulting, although loading the same DLL from another C++ program worked fine. Another round of investigation began…

To cut a long story short, here is the correct way to compile C code into a DLL and access it from Perl.

The C code

I’m going to write a simple C function that demonstrates some interesting concepts like passing data in and out with pointers. Here is the .h file:

int __stdcall test1(char* buf,
int num, char* outbuf);

This is a (almost) normal declaration of a function named test1 that takes two pointers to a char and one integer as arguments, and returns an integer.

__stdcall is a Visual C++ compiler keyword that specifies the stdcall calling convention. The stdcall convention is used by Windows API functions.

There’s another common calling convention - __cdecl which is usually used for “normal” (not Windows API) code. The Win32::API Perl module supports only __stdcall, so while we could use __cdecl for binding this DLL to another piece of C / C++ code, it doesn’t work with Win32::API.

The .c file provides the implementation:

#include "dll_test.h"

int __stdcall test1(char* buf,
int num, char* outbuf)
{
int i = 0;

for (i = 0; i < num; ++i)
{
outbuf[i] = buf[i] * 3;
}

return num;
}

Read more


User reviews

There are no user reviews for this item.

Add new review




Powered by jReviews

Last Updated ( Monday, 21 January 2008 )
 
< Prev   Next >