Skip to content Skip to sidebar Skip to footer

Cython: Overloaded Constructor Initialization Using Raw Pointer

I'm trying to wrap two C++ classes: Cluster and ClusterTree. ClusterTree has a method get_current_cluster() that instantiates a Cluster object, and returns a reference to it. Clust

Solution 1:

Pointers can only be passed to cdef'd functions as arguments, and cinit has to be def'd. But providing a classmethod is almost the way to go!

cdef Cluster* __thisptr
cdef bool __wrapped  ## defaults to False

@staticmethod
cdef PyCluster wrap(Cluster* ptr):
    cdef PyCluster pc = PyCluster([], [])  ## Initialize as cheaply as possible
    del pc.__thisptr  ## delete the old pointer to avoid memory leaks!
    pc.__thisptr = ptr
    pc.__wrapped = True
    return pc

Solution 2:

I know this is an old question, but after my own recent struggles with Cython I thought I'd post an answer for the sake of posterity.

It seems to me you could use a copy constructor to create a new PyCluster object from an existing Cluster object.

Define the copy constructor in your C code, then call the copy constructor in the Python class definition (in this case, when a pointer is passed) using new. This will work, although it may not be the best or most performant solution.


Post a Comment for "Cython: Overloaded Constructor Initialization Using Raw Pointer"