[C++-sig] Re: a working example of wrapping an instantiated c++ object

David Abrahams dave at boost-consulting.com
Sun Dec 5 18:24:32 CET 2004


Yao Heling wrote:
 > Hi,
 >
 > As I'm rather new to boost::python, I have spent quite
 > some time to find
 > solutions to this problem. I havn't spotted similar
 > examples in the
 > libs/python/test dir. By the way, it's based on a
 > previous mailing list
 > discussion; what I did was basically put everything
 > together. (a cpp
 > file and a py test file).
 >
 > Could someone pls add it to the example dir of boost
 > if there's no such
 > example?


I'd be happy to, but...

 > ------------------------------------------------------------------------
 >
 > //based on c++sig mailing list discussions
 > //http://thread.gmane.org/gmane.comp.python.c++/6980
 >
 > //It's often quite common, especially in gui programs, to export an 
instantiated c++ object to python instead of the class. e.g. to add 
scripting to an gui program, it's sometimes necessary to export the 
window handle to python
 >
 > #include <boost/python.hpp>
 > namespace bp = boost::python;
 >
 > class A {
 >     public:
 >         A(int x): _x(x) {}
 >         int f() { return 100; }
 >         int value() {return _x;}
 >     private:
 >         int _x;
 > };
 >
 > // this is the object to export
 > A a(99);
 >
 > // a helper function
 > A* get_existing()
 > {
 >     return &a;
 > }
 >
 > //turn a c++ func to a boost::python func
 > bp::object py_get_existing = bp::make_function(
 >         &get_existing,
 >         bp::return_value_policy<bp::reference_existing_object>()
 >         );
 >
 >
 > BOOST_PYTHON_MODULE(object_only_ext)
 > {
 >     //wrapping the functions of A as usual
 >     bp::class_<A, A*, boost::noncopyable> classA("A",bp::no_init);
 >
 >     classA
 >         .def("f", &A::f)
 >         .def("value", &A::value);
 >
 >     //gain access to a boost::python object to wrap it
 >     bp::object py_a = py_get_existing();
 >     bp::def("a", py_a);

Doesn't something like:

       bp::scope().attr("a") = object(ptr(&a));

Work just as well, with no need to build wierd helper functions?

--
Dave Abrahams
Boost Consulting
http://www.boost-consulting.com




More information about the Cplusplus-sig mailing list