|
From: Ben W. <be...@sa...> - 2006-02-23 01:34:32
|
John Pye wrote:
> I'm having trouble using Py_BuildValue to pass a SWIG-wrapped *C++
> object* back to my python callback function. It says in the python docs
> that I can pass a PyObject using the "o" string, but I'm not sure how I
> can cast my C++ object to a PyObject from inside C++. What's the correct
> way of doing that?
May or may not be of use to you, but we do something similar for our
package (mixed Fortran 90 and C code - don't ask!). The C/Fortran
objects simply keep a borrowed reference to the corresponding Python
object (note: we don't use shadow classes or SWIG-generated
constructors) which is used for callback functions.
For example, a typical constructor looks like:
struct foo *new_foo(const void *scriptobj)
{
struct foo *newobj;
newobj = .../* create new struct foo object */
newobj->scriptobj = scriptobj;
return newobj;
}
The SWIG interface then looks something like:
/* Pass scripting language objects to new_foo() routines as
opaque void * */
%typemap(in) const void * scriptobj {
$1 = $input;
}
and the Python class looks something like:
class foo(object):
def __init__(self):
self.this = _module.new_foo(self)
def __del__(self):
_module.free_foo(self.this)
(Note that we don't Py_INCREF the passed object, since the lifetime of
the C/Fortran and Python objects should be the same, and we don't want
circular references.)
Ben
--
be...@sa... http://salilab.org/~ben/
"It is a capital mistake to theorize before one has data."
- Sir Arthur Conan Doyle
|