[C++-sig] Boost.Python Metaclass

James Emerton ephelon at gmail.com
Wed Feb 16 04:12:15 CET 2011


Given a C++ class wrapped with Boost.Python:

class CPPClass {
  void test();
}

BOOST_PYTHON_MODULE(testmodule)
{
  class_<CPPClass>("CPPClass")
    .def("test", &CPPClass::test)
    ;
}

I've created a python subclass and redefined the metaclass:

class Meta(CPPClass.__class__):
  def __new__(cls, name, bases, attrs):
    return super(Meta, cls).__new__(cls, name, bases, attrs)

class PyClass(CPPClass):
  __metaclass__ = Meta


Any attempt to call methods of PyClass, or to pass it as an argument to a C++ function results in an ArgumentError.  It appears that ob_type is being tested for equivalence to the Boost.Python.class type.

I am currently working around this by using a plain function as the metaclass, but it's not ideal as each base class must set the metaclass explicitly.


I browsed through object/class.cpp, and I think using PyType_IsSubtype() in place of == &class_metatype_object should be sufficient to allow me to derive metaclasses from Boost.Python.class.  

Does anyone have any advice, comments or objections before I proceed? 

James



More information about the Cplusplus-sig mailing list