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

Jim Bosch talljimbo at gmail.com
Wed Mar 3 03:33:48 CET 2010


On Wed, 2010-03-03 at 07:48 +0530, puneet goel wrote:
> Mathew/Jim
> 
> > If you just need your Python interface to support calling those function
> > pointers, not adding new functions in Python, it's relatively easy.
> 
> Thanks for your support.
> 
> Actually I need to pass data from Python to C++.  I am required to
> pass Python functions as part of the structure in a way that these get
> executed somewhere in C++.
> 
> Now that I know that this can not be done in a straightforward manner,
>  I am looking for a workaround. I would like to know whether it is at
> all possible to pass a Python function, as data, to C++ using
> boost-python. What would be the C++ type of a structure element that
> would be able to hold a Python function when passed using
> boost-python?
> 
> To clarify, if I get the C++ API changed to something like
> 
> struct foo {
> public:
>  int a, b;
>  char *str;
> 
>  foobar func1;
>  foobar func2;
> };
> 
> What type (in C++) would foobar be so that I am able to pass a python
> function for func1 and func2?

boost::python::object - it's just a smart pointer to an arbitrary Python
object (in the Python C-API, it's PyObject*).  It overloads operator()
to invoke the underlying Python object's __call__ method, and it's
templated to take a reasonable number of arbitrarily typed arguments,
convert them to Python, and feed them to the Python method.


Jim




More information about the Cplusplus-sig mailing list