I’m trying to create a custom type in CPython that inherits from an already defined type object in Python. My approach thus far is to use PyImport_ImportModule
, then access the PyTypeObject
and set it to the tp_base
attribute in my PyTypeObject
.
The following is an incredibly hacky attempt to do so.
Importing:
PyTypeObject typeObj = {...} // Previously defined PyTypeObject for a fallback
int init() {
PyObject* obj = PyImport_ImportModule("<absolute_path_to_python_module>");
if (obj && PyObject_HasString(obj, "<python_type_object>")) {
PyTypeObject* type_ptr = (PyTypeObject*) PyObject_GetAttrString(obj, "<python_type_object>");
typeObj = *type_ptr;
}
if (PyType_Ready(&typeObj) < 0) return -1;
... // Other initialization stuff
}
Inheriting:
PyTypeObject CustomType = {
... // Initialization stuff
.tp_base = &typeObj;
};
The custom type is able to inherit the functions, but fails on isInstance(CustomType(), TypeObj)
. When I try to access the __bases__
attribute of the custom type, it raises a segmentation fault.