6/05/2006

Easy Perl callbacks for SWIG

Took me a bit of time to figure this out. SWIG is an excellent tool for wrapping C++ libraries such that they become callable from scripting languages. The one thing I found lacking (and I think many others have too) is the inability to register perl code as a C/C++ callback.
The people who maintain SWIG like to do this with something they call a "director", which is basically a way to let you override virtual functions from the scripting language. I see two problems with that:
1 - There's no Perl support for it yet, and there doesn't seem to be any coming
2 - Doing callbacks by overriding classes is a pain in the butt. If I want (e.g.) a button press to be labeled "quit" and to quit the program when pressed, I should be able to pass in: sub{ exit(0); } to the button, not override a silly buttonListener class.
Anyway, stealing liberally from code I've found on the net, I managed to put together something very easy and usable. It also makes use of the excellent boost::function and boost::bind wrappers, but allows you to pass a perl anonymous subroutine or subroutine refrence as if it were either a void(void) C function, or a boost::function. That means there's no way to support a closure (which you don't need because Perl supports them on anonymous subs directly), and there's no way for the callback to pass an argument back (but you could just pass something in when you register the callback anyway).

Without further ado, here's a header to be swigged and included before any callback is defined, that should make using Perl subs as C++ callbacks completely transparent:
PerlFunction.h

2 Comments:

Anonymous Anonymous said...

Hi.
Off the subject of your latest post,
Rikai.com seems to be off line, though the site is there, I can't plug Jpns pages into it anymore. THere is no notice up, but are you doing renovations?

3:29 AM  
Blogger bob said...

How does one use PerlFunction to register a callback that expects an argument? I'm only able to get boost::function< void(void)> callbacks to work.

3:42 AM  

Post a Comment

Links to this post:

Create a Link

<< Home