[C++-sig] Subclassing C++ classes in Python

Ernie Lee tr.ernie.l at gmail.com
Mon Mar 16 01:34:06 CET 2015


Hi there,

  I am creating binding for some C++ classes and I need to be able to
subclass exposed C++ classes in Python (and pass subclassed instances back
in to C++ code).

  I was able to make this work by following this example:
http://www.boost.org/doc/libs/1_57_0/libs/python/doc/tutorial/doc/html/python/exposing.html#python.class_virtual_functions
and creating binding for both: original C++ classes and ‘wrapper’ structs.
This however create inconvenience and path for errors because now users
need to remember to use different base class when subclassing C++ classes.
Is there is a way to achieve subclassing functionality by exposing one
class instead of two?

  When I tries to use class exposed as ’wrapper’ as substitute for C++
original class i am getting a segfault error (see example below). Is there
is something wrong with a way i create a wrapper-class or it is not
intended to work as substitute for a base class?

  Thanks,

Ernie.


Python code: ————————
from subclass import *

class B(A_Wrapper):
    def __init__(self): A_Wrapper.__init__(self)

    def info(self): print 'B info!'

a = A(); a.info(); print '1'
b = B(); b.info(); print '2'

aw = A_Wrapper(); print '3'; aw.info(); print '4' # <-- segfault before '4'
got printed


C++ code: ————————
#include <iostream>
#include <boost/python.hpp>

class A
{
public:
virtual ~A() { std::cout << "A destructor for object: " << this <<
std::endl; }

virtual void info() { std::cout << "C++ A info for object" << this <<
std::endl; }
};


struct A_Wrapper : A, boost::python::wrapper<A>
{
A_Wrapper() : A() {}

void info() {this->get_override("info")(); }
};


BOOST_PYTHON_MODULE(subclass)
{
boost::python::class_<A, boost::noncopyable>("A")
.def("info", &A::info)
;

boost::python::class_<A_Wrapper, boost::noncopyable>("A_Wrapper",
 boost::python::init <>() )
.def("info", &A_Wrapper::info)
;
}
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/cplusplus-sig/attachments/20150315/9224b308/attachment.html>


More information about the Cplusplus-sig mailing list