Saturday, December 2, 2006

Python/C++ using SWIG (MSVS7.1)

Petros and I got a "hello world" class exposed to Python as a DLL/module using SWIG. We ran into a few problems along the way. Nothing big, but some hang-ups that surely everybody must run into, so I thought I'd share the war story.

First, to get "natural" python syntax for your exposed C++ objects, you'll need to use Shadowing. This is a SWIG command-line option that creates a Python script file that wraps the C++ DLL containing your exposed class. Since the Python interpreter will import either DLL's or scripts, you need a new name for your C++ DLL, such as _moduleName.dll. The your shadow script is just moduleName.py. Note that the shadow script is named with lower-case letters, ignoring the case specified in the .i file.

When a Python module is loaded, it calls initModulename(). SWIG generates, instead, an initialization function called init_Modulename(). Creating a trivial initDance() that calls init_Dance()worked fine.

Finally, the standard Python binary distribution for Win32 doesn't include the debug versions of the libs. This is a problem because it is apparently using #pragma link to reference the appropriate libs-- so debug builds fail. One hack is to specify the option /U "_DEBUG" (for Visual Studio) on just the SWIG-generated C++ file (dance_wrap.cxx for the DANCE module).

No comments: