[C++-sig] Passing wrapped objects between extensions via python.

Gerard Brunick gbrunick at andrew.cmu.edu
Fri May 4 18:02:46 CEST 2007


I'd like to be able to add new C++ code "on the fly."  I have the "main" 
extension module:
*************************
#include <iostream>
#include <boost/python.hpp>
#include <boost/function.hpp>

void do_function(boost::function<double (double)> func, double arg) {
    std::cout << "Doing function: " << func(arg) << std::endl;
}

BOOST_PYTHON_MODULE(main) {
    boost::python::class_<boost::function<double (double)> 
 >("double_double");
    boost::python::def("do_function", do_function);
}
***************************

Later I decide to add functionality (during a session in which the 
python is running
and the main extension module has been loaded) so I compile a new 
extension module:

***************************
#include <boost/python.hpp>
#include <boost/function.hpp>

double triple(double d) { return d * 3; }

BOOST_PYTHON_MODULE(helper) {
    boost::python::scope().attr("triple")
        =  boost::function<double (double)>(triple);
}
****************************

This all seems to work fine.  In fact I have

*********
 >>> import main, helper
 >>> main.do_function(helper.triple, 3)
Doing function: 9
**********

but

****************
 >>> import helper, main
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: No to_python (by-value) converter found for C++ type: class 
boost::function<double __cdec
l(double),class std::allocator<void> >
*****************

which I take to be a good thing, because it means that helper actually 
finds the to_python
converter in main.  The thing is, I'm a little uneasy about all of this 
because I feel that
I should have to do something to make the helper.pyd link again the 
main.pyd.  Is it really this
easy, or am I doing something that is unsafe?

Thanks,
Gerard



More information about the Cplusplus-sig mailing list