gpt4 book ai didi

python-3.x - 如何从 Python C 扩展访问子类的对象结构字段?

转载 作者:行者123 更新时间:2023-12-03 11:28:02 25 4
gpt4 key购买 nike

我正在编写一个包装外部 C 库的 Python C 扩展。在原始库中有结构(为便于讨论,类型为 T),因此我的扩展类如下所示:

typedef struct {
PyObject_HEAD
T *cdata;
} TWrapperBase;

我也时不时需要查一下Python中的指针,所以暴露了一个只读字段_cdata,就是一个cdata指针为unsigned long long(是的,我知道它不是很便携,但现在超出了范围)。

然后,我希望能够在 Python 中添加更多方法,但我不能将它们附加到 C 中声明的类中,因此我将其子类化并添加我的新方法:

class TWrapper(TWrapperBase):
...

现在,在我的 C 扩展代码中,我需要一种访问 cdata 字段的方法,这样我就可以将它传递给库函数。我知道 self 不会是 TWrapperBase 的实例,而是 TWrapper(这个 Python 版本)。 执行此操作的正确方法是什么?

static PyObject * doStuff(PyObject *self)
{
T *cdata_ptr;
// How to get a pointer to cdata?
//
// This looks very unsafe to me, do I have any guarantee of
// the subclass memory layout?
// 1. cdata_ptr = ((TWrapperBase*)self)->cdata
//
// This is probably safe, but it seems to be a bit of a hassle
// to query it with a string key
// 2. cdata_ptr = PyLong_AsVoidPtr(PyObject_GetAttrString(self, "_cdata"))
do_important_library_stuff(cdata_ptr);
Py_INCREF(self);
return self;
}

谢谢!

最佳答案

  // This looks very unsafe to me, do I have any guarantee of
// the subclass memory layout?
// 1. cdata_ptr = ((TWrapperBase*)self)->cdata

是的,那行得通。你可以看看 Python's built-in types 的所有实现并看到它们做几乎相同的事情,通常不检查它们是否在子类实例上运行。

关于python-3.x - 如何从 Python C 扩展访问子类的对象结构字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37015397/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com