[C++-sig] shared_ptr and register_ptr_to_python

Jim Bosch talljimbo at gmail.com
Sun Oct 10 03:47:20 CEST 2010


On 10/09/2010 03:54 AM, Marek Denis wrote:
> Hello list,
>
> What I am trying to achieve is a part of C++ code operating on some data
> nad 'putting' some C++ defined (as well as Python exposed) objects into
> the Python blocking queues.
> Is there any possibility for Python to work directly on the C++ objects?
> Right now, when I launch the Python function from withing the C++ code,
> passing the POINTER (just normal pointer) od my objects what I can
> observer is a process of creating and copying the new object in Python.
> I can then operate on this object and so on, however I truly believe
> that working on the same object would be faster.
> Another problem is that I need to use some polymorphism functionality,
> so I would like to be able to put a object of type Derived from withing
> C++ code, get it from the Python perspective as Base object and launch
> virtual function (which would be Derived::f in this case).
> I am still not sure whether passing shared_ptr and using
> register_ptr_to_python is what I really need, wherether there is ANY
> possibility to do what I actually need. In other words I am creating
> objects with C++ but want to operate on them with Python, preferably
> with all the polimorphism and that fancy stuff. Any code snippets,
> suggestions?
> BTW. What options shall I pass to g++ in order to use shared_ptr?
> Thank you in advance,
>

Pretty much everything you need should automatically work, whether you 
use shared_ptr or raw pointers with call policies.  If you've invoked 
register_ptr_to_python on all the classes you're using, you'll find that 
in Python you'll always get the most-derived class, even if it's 
returned as a base class pointer or smart pointer on the C++ side.

You shouldn't need any extra compiler flags.  Just use Boost.Python the 
way described in the tutorial, and throw in some register_ptr_to_python 
invocations - that should be all you need.

HTH!

Jim Bosch


More information about the Cplusplus-sig mailing list