有没有办法将 PyTypeObject 从 Python 库继承到 CPython 中的自定义类型?

Is there a way to inherit a PyTypeObject from a Python library into a custom type in CPython?

我正在尝试在 CPython 中创建自定义类型,它继承自 Python 中已定义的类型对象。到目前为止,我的方法是使用 PyImport_ImportModule,然后访问 PyTypeObject 并将其设置为 PyTypeObject.

中的 tp_base 属性

正在导入:

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
}

继承:

PyTypeObject CustomType = {
    ... // Initialization stuff
    .tp_base = &typeObj;
};

自定义类型可以继承功能,但在isInstance(CustomType(), TypeObj)上失败。当我尝试访问自定义类型的 __bases__ 属性时,它引发了分段错误。

类型由标识而非值标识。当您尝试执行 typeObj = *type_ptr; 时,即使它“有效”,typeObj*type_ptr 具有不同的内存地址,并且永远不会被视为同一类型。您需要保留身份。

将您的代码更改为:

PyTypeObject fallback_type_obj = {...} // Previously defined PyTypeObject for a fallback
PyTypeObject *type_ptr = NULL;

int init() {
    PyObject* obj = PyImport_ImportModule("<absolute_path_to_python_module>");
    if (obj && PyObject_HasString(obj, "<python_type_object>")) {
        type_ptr = (PyTypeObject*) PyObject_GetAttrString(obj, "<python_type_object>");
    }
    if (type_ptr == NULL) {
        if (PyType_Ready(&fallback_type_obj) < 0) return -1;
        type_ptr = &fallback_type_obj;
    }
    ... // Other initialization stuff
}

然后创建一个使用 type_ptr 作为基础的堆类型(static/global 类型将不起作用,因为 type_ptr 未静态初始化为任何有用的东西)。