[C++-sig] test if object instance is instance of extension class in C++

Holger Joukl Holger.Joukl at LBBW.de
Fri Feb 24 11:44:40 CET 2012


Stefan,

many thanks, that of course did the trick. I'm not seeing the wood for the
trees
any more, I fear.

> > what's the recommended way to check if an object instance is an
instance of
> > my extension class
> > in C++ code?
> >
> > I'm currently doing a very ugly
> >
> > #define isMyExtensionClass(pyobj) (strcmp(pyobj->ob_type->tp_name,
> > "MyExtensionClass") == 0)
> >
> > on PyObj* pyobj.
> >
> > I bet there is a better way but just can't seem to find it.
>
> bpl::extract<MyExtensionClass> e(pyobj);
> if (e.check()) ...
>
> Note that you may want to use a reference type as template argument to
> the boost::python::extract type, if you want to retrieve the object by
> reference instead of by value.
>
> See http://www.boost.org/doc/libs/1_40_0/libs/python/doc/v2/extract.html
> for details.

Just for the record, this is what I do now:

inline
bool isMyExtensionClass(PyObject* &pyobj) {
    bp::extract<MyExtensionClass&> extractor(pyobj);
    return extractor.check();
}


inline
bool isMyExtensionClass(bp::object &obj) {
    bp::extract<MyExtensionClass&> extractor(obj);
    return extractor.check();
}

Thanks again & have a nice weekend
Holger

Landesbank Baden-Wuerttemberg
Anstalt des oeffentlichen Rechts
Hauptsitze: Stuttgart, Karlsruhe, Mannheim, Mainz
HRA 12704
Amtsgericht Stuttgart



More information about the Cplusplus-sig mailing list