Boost C++ Libraries of the most highly regarded and expertly designed C++ library projects in the world. Herb Sutter and Andrei Alexandrescu, C++ Coding Standards

This is the documentation for an old version of Boost. Click here to view this page for the latest version.

Chapter 4. Frequently Asked Questions (FAQs)

How can I wrap a function which takes a function pointer as an argument?
I'm getting the "attempt to return dangling reference" error. What am I doing wrong?
Is return_internal_reference efficient?
How can I wrap functions which take C++ containers as arguments?
fatal error C1204:Compiler limit:internal structure overflow
How do I debug my Python extensions?
Why doesn't my *= operator work?
Does Boost.Python work with Mac OS X?
How can I find the existing PyObject that holds a C++ object?
How can I wrap a function which needs to take ownership of a raw pointer?
Compilation takes too much time and eats too much memory! What can I do to make it faster?
How do I create sub-packages using Boost.Python?
error C2064: term does not evaluate to a function taking 2 arguments
How can I automatically convert my custom string type to and from a Python string?
Why is my automatic to-python conversion not being found?
Is Boost.Python thread-aware/compatible with multiple interpreters?

If what you're trying to do is something like this:

typedef boost::function<void (string s) > funcptr;

void foo(funcptr fp)


And then:

>>> def hello(s):
...    print s
>>> foo(hello)
hello, world!

The short answer is: "you can't". This is not a Boost.Python limitation so much as a limitation of C++. The problem is that a Python function is actually data, and the only way of associating data with a C++ function pointer is to store it in a static variable of the function. The problem with that is that you can only associate one piece of data with every C++ function, and we have no way of compiling a new C++ function on-the-fly for every Python function you decide to pass to foo. In other words, this could work if the C++ function is always going to invoke the same Python function, but you probably don't want that.

If you have the luxury of changing the C++ code you're wrapping, pass it an object instead and call that; the overloaded function call operator will invoke the Python function you pass it behind the object.