swig and python/C++ (embedded)

Dave Marotti landshark at verticaladdiction.net
Mon Aug 26 03:17:07 CEST 2002


I have 2 questions regarding embedding python into C++ with SWIG.

First some overview:

I wrote a small application as a test to see if I could successfully wrap a C++
class with SWIG, and then embed python into C++ and access my wrapped
functionality via PyRun_SimpleString() calls.  It works, kind of.

The problem I'm having is that I cannot seem to directly call "SWIG_init()"
from my main() function to initialize the wrapped module.

I've tried creating prototypes and extern prototypes at the top of my main c++
file such as:

extern "C" void SWIG_init();
void SWIG_init();

But when I compile, I get an undefined reference to SWIG_init() (yes I'm
compiling the xxx_wrap.cxx file too.

So what I did is modify the xxx_wrap.cxx file and add this:

void duh() {

Then in my main file I added:

void duh();

and calling duh() works to initialize the wrapped module().

It's a hack, but it works.  

Question 1.

Does anyone know how I can get around having to
modify the wrapped file?  It's easy enough to incorporate this hack into the
Makefile for auto-generation, but I hate doing it, it feels wrong.

Question 2.

Now that I have this working, I want to call python functions from C++ that
expect the wrapped object as an argument.

Can anyone give some advice on how I can create a PyObject out of my real C++

My wrapped class is called "Stack" (a LIFO).

say you have a function in python:

def someFunc(Stack s):
    # do something here with s

I want to call this from C++, but I'm not sure how to go about constructing the
PyObject to pass to the function call.

Any ideas/pointers?

I appreciate any comments this, as it has me sorta stumped.


| Dave Marotti                | Looking for a Visio alternative for *nix?    |
| lndshark ! speakeasy net    | Kivio : http://thekompany.com/projects/kivio |
| I just don't trust anything | Duct tape is like the force.  It has a light |
| that bleeds for 5 days and  | side and a dark side, and it holds the       |
| doesn't die. - Mr. Garrison | universe together.  - Carl Zwanzig           |

More information about the Python-list mailing list