[C++-sig] shared_ptr and register_ptr_to_python
Jim Bosch
talljimbo at gmail.com
Sun Oct 10 20:15:15 CEST 2010
On 10/10/2010 03:58 AM, Marek Denis wrote:
> On 10.10.2010 03:47, Jim Bosch wrote:
>>
>> 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,
>
> That's what I couldn't get while reading Boost tutorial (the example
> code didn't work either :( ).
> Let's say I have three classes:
>
> class A {};
> class B : public A {};
> class C : public B {};
>
> should I later just put:
> register_ptr_to_python< A >();
> register_ptr_to_python< B >();
> register_ptr_to_python< C >();
> ?
Actually, you want something like this:
register_ptr_to_python< boost::shared_ptr<A> >();
If you want to use raw pointers, I don't think you need
register_ptr_to_python (see below).
> Here is the small code snippet:
>
> +v
> boost::python::call_method<void>(callback,"addToQueue",c);
> -v
>
> where callback is a PyObject* pointer,and 'c' is a pointer to the object.
> Whenever I call this instruction, I can see that the 'c' object is being
> copied (I just put some cout << "debug" << endl in the definition of the
> Copy Constructor), so I assumed that Python code doesn't operate on the
> object that was created in C++ module. Instead, it just operates on the
> copy.
>
I'm actually kind of surprised about this - in other circumstances
(particularly when returning values in wrapped functions by pointer),
Boost.Python doesn't copy pointers or references unless you explicitly
ask it to. One thing that may be worth trying: when you wrap C Python,
mark it as noncopyable:
class_<C,bases<B>,boost::noncopyable>("C")
I'd be curious to see what happens with your call_method code snippet
with that in place.
In any case, if you're willing to use shared_ptr everywhere instead of
raw pointers, and switch your register_ptr_to_python calls as I've shown
above, I think that will also stop any copying that's going on here.
There should be a way to do it with raw pointers too, but I don't see it
yet (and it may not exist).
Jim
More information about the Cplusplus-sig
mailing list