Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
491 views
in Technique[技术] by (71.8m points)

python - Handling pointers when wrapping C++ class with Cython

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)        

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'

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;
}

NOTE: I can't solve it by holding a Person instance (cdef Peron not_pointer) for other reasons involving the complete class.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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).

In concrete, the answer to my problem is to write cdef Person new_father=dereference(father.c_person).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...