我正在尝试使用一个 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
直接传递 glp_tree 对象似乎可以工作(尽管这不是我想要做的),但尝试传递指针会导致编译器错误:
Cannot convert 'glp_tree *' to Python object
而不是使用__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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)