[C++-sig] Smart Pointers in Boost.Python with Automatic Dereferencing

Bilokon, Paul paul.bilokon at lehman.com
Mon May 19 14:30:59 CEST 2008


Hi all,

I'm trying to find an authoritative resource on exposing functions that
return smart pointers using Boost.Python.

So far my best example is this:

http://wiki.python.org/moin/boost.python/PointersAndSmartPointers

However, I find the need to explicitly dereference the pointer in Python
deeply unsatisfactory:

print (+an_A).hello()

This is essentially C++ programming in Python. The whole purpose of the
exercise is to avoid the need for explicit memory management!

Is there another method that will simply allow me to call

print an_A.hello()

Many thanks for your help!

Best wishes,
Paul


P.S. Just for your information I'll paste the C++ code:

#include <boost/shared_ptr.h> 
using namespace boost;

struct A {
    shared_ptr<A> create () { return shared_ptr<A>(new A); }
    std::string   hello  () { return "Just nod if you can hear me!"; }
};

BOOST_PYTHON_MODULE(shared_ptr)
{
    class_<A>("A",init<>())
        .def("create",&A::create,return_value_policy<return_by_value>())
        .staticmethod("create")
        .def("hello",&A::hello)
        ;

    class_< shared_ptr<A> >("A_ptr", init<const shared_ptr<A>& >())
 
.def("__pos__",&boost::shared_ptr<A>::get,return_internal_reference<>())
        ;
}

And the sample Python program:

from shared_ptr import *
an_A = A_ptr.create()
print (+an_A).hello()
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

This message is intended only for the personal and confidential use of the designated recipient(s) named above.  If you are not the intended recipient of this message you are hereby notified that any review, dissemination, distribution or copying of this message is strictly prohibited.  This communication is for information purposes only and should not be regarded as an offer to sell or as a solicitation of an offer to buy any financial product, an official confirmation of any transaction, or as an official statement of Lehman Brothers.  Email transmission cannot be guaranteed to be secure or error-free.  Therefore, we do not represent that this information is complete or accurate and it should not be relied upon as such.  All information is subject to change without notice.






More information about the Cplusplus-sig mailing list