在 cython 类中包装一个预初始化的指针

Sno*_*gus 6 c python pointers cython

我正在尝试使用一个 C 库,它使用一个回调函数 (callback_function) 来提供一个指向我想要包装的结构 (glp_tree) 的指针。

使用未在 中创建的指针初始化实例的正确方法是什么__cinit__?我在 cython 文档中找不到这种模式的例子。

我有一些工作代码(见下文),它将指针转换为整数并返回,但我不确定这是好的做法/理智。

cdef extern from "stdint.h":
    ctypedef unsigned long long uint64_t

cdef extern from "glpk.h":
    ctypedef struct glp_tree:
        pass

cdef void callback_func(glp_tree* tree, void *info):
    treeobj = Tree(<uint64_t>tree) // cast to an integer...

cdef class Tree:
    cdef glp_tree* ptr
    def __init__(self, uint64_t ptr):
        self.ptr = <glp_tree*>ptr // ... and back to a pointer
Run Code Online (Sandbox Code Playgroud)

直接传递 glp_tree 对象似乎可以工作(虽然这不是我想要做的),但是尝试传递指针会导致编译器错误:

Cannot convert 'glp_tree *' to Python object
Run Code Online (Sandbox Code Playgroud)

Dan*_*iel 7

您可以使用自定义来创建实例,而不是使用__init__/ __cinit__(它总是期望 Python 对象作为参数)@staticmethod cdef

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
Run Code Online (Sandbox Code Playgroud)