Python and SWIG - passing object pointer param to an embedded script.

Andrew Bonello andrew.bonello at metrics.co.uk
Wed Mar 28 04:22:17 EST 2001


Good Day

I have a query as regards embedded Python scripts and the Python/C API.

I am invoking evaluation of a Python script from within my C++ code using
the PyRun_File(...) function. I want to be able to pass a pointer to one of
my PyObject-derived C++ objects into this script as a parameter. Then,
within the Python script, I want to be able to pass this parameter to
function calls in an imported module defined using a SWIG interface, which
invokes C++ code in a DLL that I have written.

What I am trying to do here is to be able to work in my wrapping C++ code,
creating and modifying the state of some (PyObject-based) C++ objects, then
invoke an embedded Python script, which in turn calls some C++ functions
defined in my SWIG module. Those functions may themselves modify the state
of my outer C++ objects, so clearly I need some way of linking the objects
into my script environment when the Python interpreter is run.

I have tried to do this as follows:

// intialise python interpreter
Py_Initialize();

std::string m_FileName = "./test.py";
FILE* fp = fopen( m_FileName.c_str(), "r" );
const char* fn = m_FileName.c_str();

PyObject *globals = PyDict_New();
PyObject *locals = PyDict_New();

// this is my outer C++ object which I want Python and any SWIF functions
called to have access to
PyObject* myobj = new MyPyObj();

PyDict_SetItemString( globals, "myobjptr", myobj);

PyObject* obj = PyRun_File( fp, (char*)fn, 0, globals, locals );

This just causes an access violation. (I am using Microsoft Visual C++ V6.0
with Python V2.0, Debug build).

It seems to me that what I really ought to be doing is getting a reference
to the *exisiting* global dictionary and adding my object pointer to that,
rather than constructing a new dict using PyDict_New() - can anyone offer
any help on this?

Furthermore, my "MyPyObject" derived class may not yet be a valid PyObject.
I have been unable to find examples of how to write code for and correctly
initialise a simple C++ object which inherits from the PyObject class and
can thus be accessed from within embedded Python scripts. If anyone is able
to offer any examples of doing this, I would be most grateful.

Thanks very much!


Andy Bonello





More information about the Python-list mailing list