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
python
executable.
...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:
scripty.cc
loads and usesswig.i
which use
mappy.cc
.
Notes & Disclaimers:
python2.2
module to stay compatible with
the python2.2-dev
module. (And I switched to using
the then-bleeding-edge SWIG version 1.3.17 after starting out with
the stable-Debian 1.3.11.)
.py
file:
Py_Initialize(); initswigc(); // shadow class feature added 'c' suffix to my C-module name PyRun_SimpleString("import swigc \n"); PyRun_SimpleString("import sys \n"); PyRun_SimpleString("sys.path.append('./') \n"); PyRun_SimpleString("import swig \n"); // import the generated .py file
There are many ways to import such a thing. Use your favorite.