简体   繁体   中英

Passing a struct* from one Cython class to another

I am trying to pass a struct pointer from one Cython class to another. Here is some example code:

cdef struct MyStruct:
    int a
    int b

cdef class MyClass:
    cdef MyStruct* s
    def __init__(self):
        self.s = <MyStruct*> malloc(sizeof(MyStruct))
        self.s.a = 1
        self.s.b = 2

    cdef MyStruct* get_my_struct(self):
        return self.s

cdef class PrinterClass:
    cdef object m
    def __init__(self):
        self.m = MyClass()

    cpdef print_struct(self):
        cdef MyStruct* my_struct
        my_struct = self.m.get_my_struct()
        print(my_struct.a)

When I try to compile this class, I get these 2 errors around the my_struct = self.m.get_my_struct() line:

Cannot convert Python object to 'MyStruct *

and

Storing unsafe C derivative of temporary Python reference

Why is Cython attempting to do conversions here? Can't it just pass the pointer as is?

In PrinterClass , replace cdef object m with cdef MyClass m or explicitly cast self.m to MyClass : my_struct = (<MyClass>self.m).get_my_struct() . (In addition, a __dealloc__ should be added to MyClass ).

I guess the difference lies in that object is a python object(in essence, dict ), while cdef class is another kind of class(in essence, struct ), see Extension types (aka. cdef classes) .

Expect further revelations from other experts :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM