我正在尝试编写一个 Cython 包装器来从 Python 接口 C 代码。
C 库使用 Suitesparse 的 CHOLMOD,所以我认为安装scikit-sparse
(它使用cholmod.pyx
包含我需要的所有内容的)将是一种简洁的方式。但是,我没有成功地寻找包含 CHOLMOD 的这些定义的解决方案,并且我想避免cholmod.pxd
使用我需要的结构的 typedef 来编写“我自己的”。
作为一个最小的例子,假设我有一个foo.h
头文件,它定义了一个结构,该结构又包含一些 CHOLMOD 结构,以及一些虚拟函数。我的 Cython 定义文件如下所示:
cdef extern from "foo.h":
ctypedef struct foostruct:
cholmod_common c
cholmod_factor *f
cholmod_dense *d
void initialize_foostruct(foostruct* bar)
void modify_foostruct(foostruct* bar)
实施可以是:
from libc.stdlib cimport calloc, malloc, free
from foo cimport *
cdef class Foo:
cdef foostruct* _bar
def __cinit__(self):
self._bar = <foostruct*> calloc(1, sizeof(foostruct))
if self._bar is NULL:
raise MemoryError()
initialize_foostruct(self._bar)
def __dealloc__(self):
if self._bar is not NULL:
free(self._bar)
self._bar = NULL
def do_something(self):
modify_foostruct(self._bar)
显然这将失败,因为cholmod_common
等。在定义文件中是未知的(错误读取'cholmod_common' is not a type identifier
)。我试过类似的东西from sksparse.cholmod cimport *
,但无济于事......
有没有办法以某种方式导入这些类型标识符(来自scikit-sparse
或其他来源)以按照我的定义文件中描述的方式使用它们?