Cython - copy constructors

I have a C library that I am trying to wrap in Cython. One of the classes I create contains a pointer to a C structure. I would like to write a copy constructor that would create a second Python object pointing to the same C structure, but I am having problems because the pointer cannot be converted to a python object .

Here is a sketch of what I would like to have:

cdef class StructName: cdef c_libname.StructName* __structname def __cinit__(self, other = None): if not other: self.__structname = c_libname.constructStructName() elif type(other) is StructName: self.__structname = other.__structname 

The real problem is that the last line - it seems Cython cannot access the cdef fields from the python method. I tried to write an access method with the same result. How to create a copy constructor in this situation?

+3
cython
source share
1 answer

When playing with cdef classes, access to attributes is compiled to access members of the C-structure. As a result, to access the cdef element of object A you must be sure of type A In __cinit__ you did not tell Keaton that there was another instance of StructName . Therefore, Cython refuses to compile other.__structname . To fix the problem, just write

 def __cinit__(self, StructName other = None): 

Note: None equivalent to NULL and therefore is accepted as StructName .

If you want more polymorphism, then you need to rely on cast types:

  def __cinit__(self, other = None): cdef StructName ostr if not other: self.__structname = c_libname.constructStructName() elif type(other) is StructName: ostr = <StructName> other self.__structname = ostr.__structname 
+5
source share

All Articles