How to use PyObject_IsInstance with a non-built-in class as the second argument?

In C / C ++, I want to see if PyObject instance. Unfortunately, the PyInstance_Check macro PyInstance_Check not work with new-style classes.

So, according to the posts in the forums that I read, PyObject_IsInstance can solve the problem. However, all the examples I found demonstrate a comparison with built-in types such as int and strings.

I want to know how I can build a PyObject representing a class of type, so I can pass it into the second argument of PyObject_IsInstance . Can you help me?

+4
source share
2 answers

I finally found the answer based on the content of this page: Create an instance of the python class declared in python with the API API

 // PyInstance_Check works only for old-style classes. qBool isInstance = PyInstance_Check(pyInstance); if (!isInstance) { // It might be an instance of a new-style class. // PyRef module = PyImport_ImportModule("module.where.myclass.is"); PyObject* moduleDict = PyModule_GetDict(module.Get()); PyObject* protocolClass = PyDict_GetItemString(moduleDict, "MyClass"); int returnValue = PyObject_IsInstance(pyObject, protocolClass); } 
+1
source

You can use the corresponding PyTypeObject if it is defined in the same module. If an object of type (let it be called ProtocolType ) does not display where you want to use PyObject_IsInstance , first declare a prototype with:

 extern PyTypeObject ProtocolType; 

And then use it like this:

 PyObject_IsInstance(object, reinterpret_cast<PyObject*>(&ProtocolType) 
+1
source

All Articles