[C++-sig] Exposing a C++ function that takes 2 out arguments to python

Roman Yakovenko roman.yakovenko at gmail.com
Thu May 11 19:43:24 CEST 2006


On 5/11/06, Abhi <abhi at qualcomm.com> wrote:
> Roman, Any idea if py++ will handle this case?
> -------------
> How do I expose a C++ function that takes 2 out arguments with different
> memory ownership semantics to python. For instance,
>
> consider A, B to be user-defined types
>
> class C
> {
>     public:
>     B* b_;
>
>     void foo(A*& a, B*& b)
>     {
>         // create A on the heap and let caller take ownership
>         A* a2 =  new A()
>         a = a2;
>
>         // create B, but we retain ownership
>         b_ = new B();
>         b = b_;
>     }
>
>     ~C()
>     {
>         delete b_;
>     }
>
> };
>
> Notice that object "a" is to be destroyed in python, while "b" is owned by
> C++
>
> How do I expose this in python?
>
> I tried the following:
>
> bp::tuple foo_Wrapper(C& self)
> {
>   A* a;
>   B* b;
>   self.foo(a, b)
>   // Case1. In this case the "a" is never destroyed in python
>   // -- "a" is leaked -- NOT what I want!
>   // "b" is ok
>   make_tuple(bp::ptr(a), bp::ptr(b) );
>
>   // Case2: In this case they get copy constructed into the tuple
>   // -- that means memory for "a" is leaked!
>   // -- I don't really want a copy -- Changes the semantics, I want to
>   // modify "a" & "b" in python && it is expensive to copy
>   make_tuple(a, b);
> }
>
>
> Any other ideas?

Yes.

I could be wrong, but  from my experience boost.python does not work
well with not so good C++ code. As for me this case is one of them.

If you can redefine function foo little:

std::pair< std::auto_ptr< A >, boost::shared_ptr<B> > foo();

I think it is possible to expose this function with default value
policy, but I could
be wrong.

An other way is to define your own call policies. Take a look on:
    CallPolicies
    ResultConverter[Generator]
I don't feel, that I have enough knowledge to give you any advice in this area.

There is another issue with this code: class C has public member variable B*.
It is very difficult to expose that member.  Few weeks ago, there was
some thread
that provided solution to "get" functionality. I implemented it in pyplusplus.
I failed to implement "set" functionality.

> thanks

My pleasure

> -= Abhi
>


-- 
Roman Yakovenko
C++ Python language binding
http://www.language-binding.net/



More information about the Cplusplus-sig mailing list