[C++-sig] Boost Python: C++ struct with a function pointer

Jim Bosch talljimbo at gmail.com
Tue Mar 2 21:03:26 CET 2010

On Tue, 2010-03-02 at 16:39 +0530, puneet goel wrote:
> Greetings
> I am boost.python newbie. I tried searching the web for a solution but
> could not find one.
> I am trying to generate Python Bindings for a C++ API. The API has
> some data structures with a set function pointers as its members.
> struct foo {
> public:
>   int a, b;
>   char *str;
>   int (*func1) ();
>   int (*func2) ();
> };
> I am wondering if it is possible to bind this struct to Python. Let me
> know how this can be done.

If you just need your Python interface to support calling those function
pointers, not adding new functions in Python, it's relatively easy.  In
particular, boost::python::make_function takes a C++ function pointer
and returns a callable Python, so you can do something like this:

namespace bp = boost::python;

bp::object foo_get_func1(foo & self) {
    return bp::make_function(self.func1);

  .add_property("func1", foo_get_func1)

I haven't tested that snippet, so it may need some tweaks.  But
hopefully it will get you started.

Jim Bosch

More information about the Cplusplus-sig mailing list