[C++-sig] How to make a python function as callback of a c++ function

Holger Joukl Holger.Joukl at LBBW.de
Mon Sep 3 10:33:54 CEST 2012


Hi,

"Cplusplus-sig" <cplusplus-sig-bounces+holger.joukl=lbbw.de at python.org>
schrieb am 02.09.2012 17:00:38:


> I have to make a python function as callback of a c++ function.How
> to do?Where can I find some examples?? I want to use boost.python.
> I want my code look something like this: In C++ :

>  typedef void (*MyCallback_t) (CallbackInfo);
>  class MyClass
>  {...
>     void setcallback(MyCallback_t cb);
>   ...
>  }
>
> And to use it in python :

> import mylib
> class mypythonclass:
>     def myCallback(mylib_CallbackInfo):
>        ....
>     def mywork():
>         t = mylib.MyClass()
>         t.setcallback(self.myCallback)

A function pointer can not be wrapped in a way so that an arbitrary
python function can be used as a (callback) argument. This is due to C/C++
restrictions, see
http://www.boost.org/doc/libs/1_51_0/libs/python/doc/v2/faq.html#funcptr

Basically, a C/C++ function pointer needs to exist at compile time and
doesn't
have state while Python functions are stateful objects that come to life at
runtime.

If you have control over the C++ code you could change the signature to
take
a boost::python::object as an argument and call that, something like


//Instead of actually wrapping these...
char const * call(char const * (*func)()) {
    std::cout << "--> call" << std::endl;
    return (*func)();
}
char const * call_int(char const * (*func)(int), int i) {
    std::cout << "--> call_int" << std::endl;
    return (*func)(i);
}

// ...we expose these *instead* - note that the original call()/call_int()
aren't used at all

namespace bp = boost::python;

char const * call_wrap(bp::object &func) {
    bp::object result = func();
    return bp::extract<char const *>(result);
}
char const * call_int_wrap(bp::object &func, int i) {
    bp::object result = func(i);
    return bp::extract<char const *>(result);
}

BOOST_PYTHON_MODULE(func_ptr)
{
    bp::def("call", &call_wrap);
    bp::def("call_int", &call_int_wrap);
};


See also
http://boost.2283326.n4.nabble.com/Boost-Python-C-struct-with-a-function-pointer-td2699880.html
for some hints/discussion.

Holger

Landesbank Baden-Wuerttemberg
Anstalt des oeffentlichen Rechts
Hauptsitze: Stuttgart, Karlsruhe, Mannheim, Mainz
HRA 12704
Amtsgericht Stuttgart



More information about the Cplusplus-sig mailing list