PyInstance_New in C++ class factory

Ian Boisvert iboisver at yahoo.com
Mon Aug 30 03:10:12 EDT 2004


I'm trying to use PyInstance_New inside of a class factory to create
instances of a class that is defined in Python. I first process some
Python script that contains my class definition using the following
code:

PyObject *codeobj, *module = NULL;
codeobj = Py_CompileString(cscript, "Python script", Py_file_input);
if (codeobj != NULL)
{
	module = PyImport_ExecCodeModule("Python script", codeobj);
	if (module == NULL)
		raiseError();
}
Py_DECREF(module);
Py_DECREF(codeobj);

The call to PyImport_ExecCodeModule executes a module-scope method
that passes a class object back to the C++ code. I hold on to the
class object after incrementing it's reference count and later use it
to create instances of the class using the following code:

// create an instance of the class
PyObject *instance = PyInstance_New(classObject, NULL, NULL);
if (instance == NULL)
	raiseError();

where classObject is the class object that was passed from my Python
code back to C++.

The first time that PyInstance_New is called it works fine. The second
time it is called, it fails. I debugged the code as far as to see that
on the second call, the call to __init__ returns NULL, whereas on the
first call __init__ returns Py_None. The exception message seems to be
bogus as it mentions another method in the class that is never called.

Any suggestions as to why the second call to PyInstance_New doesn't
work would be much appreciated. Thanks.

Ian.



More information about the Python-list mailing list