用Cython处理指针时,我遇到了麻烦。该类的Cython实现将Person
类的C 实例指向。这是我的.pyx
文件:
person.pyx
cdef class PyPerson:
cdef Person *pointer
def __cinit__(self):
self.pointer=new Person()
def set_parent(self, PyPerson father):
cdef Person new_father=*(father.pointer)
self.c_person.setParent(new_father)
C 方法setParent
将Person
对象作为参数。由于PyPerson
类的属性pointer
是指向Person
对象的指针,因此我认为我可以在用语法*(PyPersonObject.pointer)
的*pointer
指向的adress上获取对象。但是,当我尝试编译时,我会收到以下错误
def set_parent(self, PyPerson father):
cdef Person new_father=*(father.pointer)
^
------------------------------------------------------------
person.pyx:51:30: Cannot assign type 'Person *' to 'Person'
有人知道如何在指针的地址中到达对象?当我在C 程序中执行相同的操作时,我没有错误。这是C 类的实现,以防您要看到它:
person.cpp
Person::Person():parent(NULL){
}
Person::setParent(Person &p){
parent=&p;
}
注意:由于涉及完整类的其他原因,我无法通过持有Person
实例(cdef Peron not_pointer
)来解决它。
我应该阅读有关使用C 与Cython一起阅读的整个Cython文档。对于那些不知道的人,取消操作员*
不能在Cython中使用。相反,您需要从cython.operator
模块导入dereference
。当您要在指向地址访问对象时,应编写dereference(pointer)
。
在具体中,我问题的答案是写cdef Person new_father=dereference(father.c_person)
。
互相解决方案可能是在位置 0
的位置索引指针,以取消Cython中的指针。例如,假设我们有一个golden_ratio c double和p_double c Pointer:
cdef double golden_ratio
cdef double *p_double
我们可以使用操作员地址&:
将golden_ratio’s
地址分配给p_double
p_double = &golden_ratio
我们现在可以使用我们的golden_ratio
分配给CC_20索引 - at-Zero-decereference 语法:
p_double[0] = 1.618
print(golden_ratio)
# => 1.618