'Cython struct inheritance and pointer casting

I am working on extending some Cython code. The existing code base relies on a struct that gets a pointer to it passed around. I am trying to use Cython with struct inheritance to extend the existing struct and still use the same function signatures, without having to extend the class (due to limitations with Cython not supporting templates).

I have the following base struct which I am trying to extend with another struct:

cdef struct Split:
   int stuff

# extended struct
cdef struct NewSplit:
   Split split
   double new_stuff

Inside my codebase, I need to use the structs in the following way:

cdef build():
   cdef Split split
   
   node_split(&split)

   _set_node_values(&split)

Finally, within the functions I need to cast Split* into a NewSplit* and set the value of new_stuff.

cdef node_split(Split* split):
    # type cast the pointer
    cdef NewSplit new_split = (<NewSplit*>(split))[0]

    # compute "new_stuff"
    new_split.new_stuff = do_func(...)

    # pass back the pointer
    split[0] = new_split.split

cdef int _set_node_values(Split* split_node):
   cdef NewSplit new_split = (<NewSplit*>(split_node))[0]
   
   # get access to the child struct members
   cdef double child_var = new_split.j

Issues

I keep getting a segfault error when I try to run the line within _set_node_values:

   # get access to the child struct members
   cdef double child_var = new_split.j

Is there a way to typecast the pointer from Split to NewSplit and vice versa?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source