[C++-sig] Boost.Python: C++ object in python: Cannot add to C++ base class list.
Christoff Kok
christoff.kok at ex-mente.co.za
Fri Oct 9 09:33:18 CEST 2015
Hi,
I am trying to extend existing C++ objects in Python via inheritance.
I can do this successfully and run virtual methods overridden in Python.
When I however, try to add the python object to a list of pointers of the
C++ Base object type(the Base object the python class has overridden), I
get a type error: 'Attempting to append an invalid type'
I am sure this error is due to there begin no 'implicitly_convertible'
functionality from derived* to base*. In C++, this would be defined as so:
implicitly_convertible<[Derived_from_base]*,Base*>();.
Is it possible to define this in python?
How can I achieve this?
Here is sample code reproducing this behaviour.
*C++*
struct Base {
virtual ~Base() {}
virtual int f() = 0;
};
struct A {
std::vector<Base*>& GetBaseList() { return m_base_List; }
std::vector<Base*> m_base_List;
};
struct BaseWrap : Base, wrapper<Base> {
int f() { return this->get_override("f")(); }
};
BOOST_PYTHON_MODULE(sandbox)
{
class_<BaseWrap, Base*, boost::noncopyable>("Base", no_init)
.def("f", pure_virtual(&Base::f));
class_<A, A*>("A", init<>())
.add_property("baseList", make_function(&A::GetBaseList,
return_internal_reference<>()));
//implicitly_convertible<[Derived_from_base]*,Base*>();
class_<std::vector<Base*>>("BaseList").def(vector_indexing_suite<std::vector<Base*>>());
}
*Python*
from sandbox import *
class derived(Base):
def __init__(self):
self.name = "test"
def f(self):
print("Hello Derived!")
d = derived()
d.f() # Output: Hello Derived!
a = A()
a.baseList.append(d) # TypeError: Attempting to append an invalid type
Any help or ideas will be greatly appreciated.
Regards,
Christoff
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/cplusplus-sig/attachments/20151009/97b7f57c/attachment.html>
More information about the Cplusplus-sig
mailing list