diff --git a/doc/v2/faq.html b/doc/v2/faq.html index 4a6448cb..3c2b4c24 100644 --- a/doc/v2/faq.html +++ b/doc/v2/faq.html @@ -29,6 +29,10 @@
+ +
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?
@@ -56,6 +60,57 @@

+

How can I wrap a function which takes a + function pointer as an argument?

+ + If what you're trying to do is something like this: +
+typedef boost::function<void (string s) > funcptr;
+
+void foo(funcptr fp)
+{
+    fp("hello,world!");
+}
+
+BOOST_PYTHON_MODULE(test)
+{
+    def("foo",foo) ;
+}
+
+ +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. + +

For more perspective on the issue, see this + posting. + +


+

I'm getting the "attempt to return dangling reference" error. What am I doing wrong?

That exception is protecting you from causing a nasty crash. It usually @@ -492,7 +547,7 @@ void b_insert(B& b, std::auto_ptr<A> a)

Revised - 23 January, 2003 + 18 March, 2003