问题描述
使用cython处理指针时遇到麻烦.该类的cython实现包含指向类Person
的C ++实例的指针.这是我的.pyx
文件:
I'm having trouble when handling pointers with cython. The cython implementation of the class holds a pointer to a C++ instance of class Person
. Here's my .pyx
file:
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
所指向的地址来获取该对象.但是,当我尝试编译它时,出现以下错误
The C++ method setParent
takes a Person
object as an argument. Since the attribute pointer
of the PyPerson
class is a pointer to a Person
object, I thought that I could get the object at the adress pointed by *pointer
with the syntax *(PyPersonObject.pointer)
. However when I try to compile it I get the following error
def set_parent(self, PyPerson father):
cdef Person new_father=*(father.pointer)
^
------------------------------------------------------------
person.pyx:51:30: Cannot assign type 'Person *' to 'Person'
有人知道我该如何到达指针的地址?当我在C ++程序中执行相同操作时,不会出现任何错误.这是C ++类的实现,以备不时之需:
Does someone knows how can I get to the object at the adress of the pointer?When I do the same in a C++ program I get no error. Here's the implementation of the C++ class in case you want to see it :
person.cpp
Person::Person():parent(NULL){
}
Person::setParent(Person &p){
parent=&p;
}
注意:由于涉及完整类的其他原因,我无法通过持有Person
实例(cdef Peron not_pointer
)来解决该问题.
NOTE: I can't solve it by holding a Person
instance (cdef Peron not_pointer
) for other reasons involving the complete class.
推荐答案
我应该阅读有关将C ++与Cython结合使用的整个cython文档.对于那些不知道的人,不能在Cython中使用解引用运算符*
.相反,您需要从cython.operator
模块导入dereference
.当您要访问指定地址的对象时,应输入dereference(pointer)
.
I should have read the entire cython docs on using C++ with Cython. For those who don't know, the dereference operator*
can't be used in Cython. Instead you need to import dereference
from the cython.operator
module. When you want to access the object at the pointed address, you should write dereference(pointer)
.
具体来说,我的问题的答案是写cdef Person new_father=dereference(father.c_person)
.
In concrete, the answer to my problem is to write cdef Person new_father=dereference(father.c_person)
.
这篇关于用Cython包装C ++类时处理指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!