question about embedding Python using C++ and SWIG

Benjamin Geer beroul at yahoo.com
Sat Oct 28 00:32:49 EDT 2000


I've been trying to figure out how to write a C++ application that
embeds a Python interpreter, into which users of the application can
feed scripts, which can in turn access the application's own C++
classes (via SWIG-generated wrappers).  I've got it working, but
there's a problem that has me perplexed.  Here's what I've done so
far:

The main problem I struggled with was this: how can the user's script,
running inside an embedded interpreter, obtain instances of shadow
classes wrapping the objects that make up the running application?  I
solved this problem by putting most of the application's classes in a
shared library, and making them accessible through a C++ singleton.
This library (including the singleton class, and the function that
provides the singleton instance) is wrapped in a SWIG-generated Python
module.  The application's command-line executable just contains a
main() function, which (in this toy example) just initialises a Python
interpreter, and feeds it a Python script supplied by the user.

The user's Python script simply needs to do this:

import fooapp # the SWIG wrapper for the application's shared library
from fooapp import Bar, Baz # some subsystems of the application

app = fooapp.getApp() # get the application singleton

# Manipulate the application
app.doThis()
app.dothat()

# Get objects representing subsystems of the application
bar = app.getBar()
baz = app.getBaz()

...etc.

Here's the problem: this only works if the Python interpreter itself
has been built as a shared library.  If I statically link
libpython2.0.a into the application's command-line executable,
something odd happens.  When the program tries to run the script
through the interpreter, Python throws this exception:

ImportError: /usr/local/lib/python2.0/lib-dynload/fooappc.so:
undefined symbol: PyInt_FromLong

Any ideas about why this might be happening?  Since I don't want to
rely on the user having gone to the trouble (on Unix) of building
Python as a shared library, I'd like to find a way around this.

Also, am I barking up the wrong tree?  Is there a better way to
accomplish what I'm trying to do?

I'm using Python 2.0 and SWIG 1.1 on a Linux system (kernel 2.2.5-15,
glibc 2.1).

-- 
Benjamin Geer
http://www.btinternet.com/~amisuk/bg



More information about the Python-list mailing list