我在使用 cython 处理指针时遇到问题。该类的 cython 实现持有一个指向该类的 C++ 实例的指针Person
。这是我的.pyx
file:
人.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
对象作为参数。由于属性pointer
of the PyPerson
类是一个指向a的指针Person
对象,我认为我可以在指向的地址获取对象*pointer
与语法*(PyPersonObject.pointer)
。但是,当我尝试编译它时,出现以下错误
def set_parent(self, PyPerson father):
cdef Person new_father=*(father.pointer)
^
------------------------------------------------------------
person.pyx:51:30: Cannot assign type 'Person *' to 'Person'
有人知道如何到达指针地址处的对象吗?
当我在 C++ 程序中执行相同操作时,我没有收到任何错误。如果您想查看的话,这是 C++ 类的实现:
人物.cpp
Person::Person():parent(NULL){
}
Person::setParent(Person &p){
parent=&p;
}
注意:我无法通过持有来解决它Person
实例 (cdef Peron not_pointer
)出于涉及整个班级的其他原因。
我应该阅读有关在 Cython 中使用 C++ 的整个 cython 文档。对于那些不知道的人,解引用运算符*
不能在 Cython 中使用。相反,你需要导入dereference
来自cython.operator
模块。当你想访问指向地址的对象时,你应该这样写dereference(pointer)
.
具体来说,我的问题的答案是写cdef Person new_father=dereference(father.c_person)
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)