gpt4 book ai didi

Cython - 复制构造函数

转载 作者:行者123 更新时间:2023-12-05 00:26:55 25 4
gpt4 key购买 nike

我有一个 C 库,我想用 Cython 包装它。我正在创建的类之一包含一个指向 C 结构的指针。我想编写一个复制构造函数来创建指向相同 C 结构的第二个 Python 对象,但我遇到了麻烦,因为指针无法转换为 Python 对象。

这是我想要的草图:

cdef class StructName:
cdef c_libname.StructName* __structname

def __cinit__(self, other = None):
if not other:
self.__structname = c_libname.constructStructName()
elif type(other) is StructName:
self.__structname = other.__structname

真正的问题是最后一行 - Cython 似乎无法从 python 方法中访问 c​​def 字段。我尝试编写一个访问器方法,结果相同。在这种情况下如何创建复制构造函数?

最佳答案

玩时cdef类,属性访问被编译为 C 结构成员访问。因此,访问 cdef对象成员 A您必须确定 A 的类型.在 __cinit__你没有告诉 Cython other 是 StructName 的一个实例.因此 Cython 拒绝编译 other.__structname .要解决问题,只需写

def __cinit__(self, StructName other = None):

注: None相当于 NULL因此被接受为 StructName .

如果你想要更多的多态性,那么你必须依赖类型转换:
 def __cinit__(self, other = None):
cdef StructName ostr
if not other:
self.__structname = c_libname.constructStructName()
elif type(other) is StructName:
ostr = <StructName> other
self.__structname = ostr.__structname

关于Cython - 复制构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21541464/

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