我有一个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
Run Code Online (Sandbox Code Playgroud)
真正的问题是最后一行 - 似乎Cython无法从python方法中访问cdef字段.我尝试过编写一个存取方法,结果相同.在这种情况下如何创建复制构造函数?
在使用cdef类时,属性访问被编译为C结构成员访问.因此,要访问cdef对象的成员,A您必须确定其类型A.在__cinit__你没有告诉Cython其他是一个实例StructName.因此Cython拒绝编译other.__structname.要解决这个问题,请写一下
def __cinit__(self, StructName other = None):
Run Code Online (Sandbox Code Playgroud)
注意: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
Run Code Online (Sandbox Code Playgroud)