[C++-sig] Boost Python smart pointers (shared_ptr)

David Abrahams dave at boostpro.com
Thu Jul 3 01:28:05 CEST 2008


Matthew Kwiec wrote:
> I am currently running Boost Python on a Debian system, and I am
> running into an error with smart pointers.  I have no problems
> with regular C++ pointers.
> 
>  
> 
> There were issues with installing Boost Python 1.35, so we rolled
> it back to one that worked on the system (1.33).  So this may be an
> issue with the version or the OS, I am not sure.

Hi Matthew,

First, I suggest you do something about your mailer; it isn't wrapping
long lines.

> After attempting much more complicated stuff that is more related to
> what I am attempting to do, I am now following the simple example that I
> have found online at
>  http://wiki.python.org/moin/boost.python/PointersAndSmartPointers:
> 
>  
> 
> #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>& >())

Don't ever wrap a shared_ptr directly; they're handled by Boost.Python
automatically.  I don't know why the wiki suggests that you do it to
support (+ptr).create(); the library will give you ptr.create()
automatically.  In fact, a non-NULL shared_ptr<A> that gets returned to
Python looks pretty much just like an A from the Python side.

>        
> .def("__pos__",&boost::shared_ptr<A>::get,return_internal_reference<>())
> 
>         ;
> 
> }
> 
>  
> 
> Running the following python commands:
> 
>  
> 
> from shared_ptr import *
> 
> an_A = A_ptr.create()
> 
>  
> 
> I keep getting the same error from the last line.
> 
>  
> 
> Traceback (most recent call last):
> 
>   File "<stdin>", line 1, in ?
> 
> AttributeError: type object 'A_ptr' has no attribute 'create'

Well, yeah.  The syntax would be

  a_ptr = A.create()
  (+a_ptr).hello()

but it seems to me that

   a = A.create()
   a.hello()

would be much cleaner.

> This makes sense to me because A_ptr doesn’t have a create
> attribute(calling A.create() does not work either), but this
> is the way the tutorial says to do it.

Well, not really; that isn't the tutorial; it's just something some
anonymous person wrote.  The tutorial is
http://www.boost.org/doc/libs/1_35_0/libs/python/doc/tutorial/doc/html/index.html

I would really appreciate it if someone could fix up that wiki page so
no further confusion ensues.

HTH,

-- 
Dave Abrahams
BoostPro Computing
http://www.boostpro.com



More information about the Cplusplus-sig mailing list