Function needs ownership of python object that is derived from a C++ class
Hi all, I have a C++ class Base that is declared as follows: struct Base { virtual int f() = 0; }; and a free function call_f that needs ownership of the parameter: void Moses::call_f(Base* b) { std::cout << " b->f() = " << b->f() << std::endl; delete (b); } On pyhton side I derive from Base like that: class Derived(Base): def f(self): return 42 of course the following leads to a segmentation fault: d = Derived() call_f(d) First thing I tried was to do this auto_ptr stuff as described in FAQ ("How can I wrap a function which needs to take ownership of a raw pointer"), but this doesn't work because of: Boost.Python.ArgumentError: Python argument types in call_f(Derived) did not match C++ signature: call_f(std::auto_ptr<Moses::Base>) then I tried to wrap call_f as follows below: call_f_Wrapper(PyObject* p) { handle<> hP(p); Moses::Base* bP = extract<Moses::Base*>(object(hP)); call_f(bP); } but this leads to segmentation faults too. Last thing I did was the stuff described in PythonInfo Wiki in section "ownership of C++ object extended in Python", but that also doesn't work and so, I guess I need your help. Best Regards, Franz
Thomas Kolb <chilavert123@gmx.net> writes:
Hi all,
I have a C++ class Base that is declared as follows: struct Base { virtual int f() = 0; }; and a free function call_f that needs ownership of the parameter: void Moses::call_f(Base* b) { std::cout << " b->f() = " << b->f() << std::endl; delete (b); }
It should take auto_ptr<Base> as an argument, if possible.
On pyhton side I derive from Base like that:
class Derived(Base): def f(self): return 42
of course the following leads to a segmentation fault: d = Derived() call_f(d)
First thing I tried was to do this auto_ptr stuff as described in FAQ ("How can I wrap a function which needs to take ownership of a raw pointer"), but this doesn't work because of: Boost.Python.ArgumentError: Python argument types in call_f(Derived) did not match C++ signature: call_f(std::auto_ptr<Moses::Base>)
Did you miss this part? Make sure the C++ object is held by auto_ptr: class_<A, std::auto_ptr<A> >("A") ... ; In your case, class_<Base, std::auto_ptr<Base> >("Base") ... ;
then I tried to wrap call_f as follows below: call_f_Wrapper(PyObject* p) { handle<> hP(p); Moses::Base* bP = extract<Moses::Base*>(object(hP)); call_f(bP); } but this leads to segmentation faults too.
I would expect so. -- Dave Abrahams Boost Consulting www.boost-consulting.com
participants (2)
-
David Abrahams -
Thomas Kolb