【发布时间】:2018-08-10 19:43:41
【问题描述】:
我正在尝试将一个结构从一个 c 文件传回我的 Python。假设我有一个像这样的文件 pointc.c:
typedef struct Point {
int x;
int y;
} Point;
struct Point make_and_send_point(int x, int y);
struct Point make_and_send_point(int x, int y) {
struct Point p = {x, y};
return p;
}
然后我像这样设置一个 point.pyx 文件:
"# distutils: language = c"
# distutils: sources = pointc.c
cdef struct Point:
int x
int y
cdef extern from "pointc.c":
Point make_and_send_point(int x, int y)
def make_point(int x, int y):
return make_and_send_point(x, y) // This won't work, but compiles without the 'return' in-front of the function call
如何将返回的结构放入我的 Python 中?这种事情只能通过在 Cython 中创建一个结构并通过引用 void c 函数来发送吗?
作为参考,我的 setup.py 是:
from distutils.core import setup, Extension
from Cython.Build import cythonize
setup(ext_modules = cythonize(
"point.pyx",
language="c"
)
)
【问题讨论】:
-
这不会是一个有用的评论,但我从来没有真正理解为什么 cython 存在。用 c 编写 python 模块比使用 cython 更容易且更好。
-
很公平,你有什么建议我直接写python模块的资源吗?我不熟悉将 c 与 python 连接起来。据我了解,Cython 有一些强大的工具,尽管使用起来有些成本。感谢您的评论!
-
是的,python官方文档。只需 google writing python modules in c 并选择您要定位的版本。这实际上是关于python的一个痛苦,2和3版本的不兼容很糟糕。
-
对比意见 - 如果您要与 python 对象进行大量交互,我认为 cython 更方便 - 没有新的 API 可以学习和引用计数簿记,这可能很微妙对,被照顾了。