Reputation: 1434
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?
Upvotes: 2
Views: 814
Reputation: 998
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 :)
Upvotes: 1