Programs: Extending Embedded Python with SWIG

2002

I wrote a C++ application that embeds the Python programming language. My Python code needs to access some C++ functionality. Thus, I extend embedded Python. This involves a lot of wrapper code.

The SWIG tool generates such wrapper code. Its documentation discusses how you can use this wrapped code

...but not how to smush it into some other executable. Here's what I came up with when I scrounged in the source:

SWIG's generated _wrap.c defines a function init_module(), where module is the module name. E.g., if your .i file has a line "%module swig", this function is named init_swig. Call this function to create the module.

extern "C" {  // I'm writing a C++ app, but initswig() is C.
    void init_swig(void); // we get this from the swig-generated file.
}
...
    Py_Initialize();
    init_swig(); 

That's it! If the .i file defines, e.g., a function HitWallP() in module swig, my Python code can now use swig.HitWallP().

My test code shows:

Notes & Disclaimers:

[>>]

comment? | | home |