Wrapping a pre-initialized pointer in a cython class

Instead of using __init__/__cinit__ (which always expects Python objects as arguments), you can use a custom @staticmethod cdef to create instances:

cdef class Tree:
    cdef glp_tree* ptr

    def __init__(self, *args):
        raise TypeError('Cannot create instance from Python')

    @staticmethod
    cdef Tree create(glp_tree* ptr):
        obj = <Tree>Tree.__new__(Tree) # create instance without calling __init__
        obj.ptr = ptr
        return obj

Leave a Comment