Callback from C++ to Python, how to pass args?
Christof Pastors
christof_n at pastors.de
Tue Aug 15 17:41:23 EDT 2000
"Bram Stolk" <bram at sara.nl> schrieb im Newsbeitrag
news:3997D0F4.A38E0F48 at sara.nl...
> Hello all,
> I've been reading chapter 1.6 "Calling Python funcs from C" of
> "Extending and Embedding the Python Interpreter".
>
> Here, an example is used that does a callback from C to a
> Python func.
> When doing this, the func Py_BuildValue() is used to build
> the argument list for the callback.
>
> This gives me problems when I want to pass objects in the
> argument list, instead of plain ints and floats.
>
> I am looking for a way to pass a ptr to a C++ object as
> an argument to the called back Python script function.
> Using the "O" formatter does not work, neither does a
> conversion to CObject first, because the script func will
> then simply get a CObject, and not a properly typed object.
>
> To clarify: the object I want to pass is a C++ object, which
> has been given Python support using SWIG.
>
> Any help greatly appreciated,
>
> Bram
Hi,
Don't know wether I undestood your question correctly. If i did, two answers
are possible:
1. If your object already was a python Object, why not pass around a
reference to it, like (with cxx-extensions)
Py::Object& l_Object;
2. If it is an Object created by C++ and no Python Shadow object exists yet,
you have to construct the shadow yourself. This is shown in the code
fragment below for a class named "CMyClass" (what a name ...)
The fragment assumes you have wrapped a C++ Class CMyClass to python with
SWIG. It
a. makes a SWIG pointer-string _ptemp from p_Obj
b. constructs a shadow-object for the C++ object that should be passed to
python by calling the PHYTHON Constructor CMyClassPtr("xxxxxxx_CMyClass_p")
c. makes the arglist l_CallbackArgs
d. Calls a Callback method of a passed in Python object named
<p_MethodName>. This is what i wanted to do, your solution will be different
at this point.
void Call_PyCallBack(Py::Object& p_rObject, char* p_MethodName,
CMyClass& p_Obj)
{
// Construct shadow of type CMyClassPtr
Py::Module l_Module(PyImport_ImportModule("MyModule"));
Py::Callable l_Ctor(l_Module.getAttr("CMyClassPtr"));
char _ptemp[128];
SWIG_MakePtr(_ptemp, (void*) &p_Obj,"_CMyClass_p");
Py::Tuple l_CtorArgs(1);
l_CtorArgs[0] = Py::String(_ptemp);
Py::Object l_MyObjPtr(l_Ctor.apply(l_CtorArgs));
// Now call Callback with new CMyClassPtr
Py::Tuple l_CallbackArgs(1);
l_CallbackArgs[0] = l_MyObjPtr;
Py::Callable callBack(p_rObject.getAttr(p_MethodName));
callBack.apply(l_CallbackArgs);
};
More information about the Python-list
mailing list