使用Cython将结构从C返回到Python [英] Return a struct from C to Python using Cython
本文介绍了使用Cython将结构从C返回到Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试将结构从c文件传递回Python。假设我有一个文件pointc.c,如下所示:
I am trying to pass a struct back into my Python from a c file. Let's say I have a file pointc.c like this:
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文件:
Then I set-up a point.pyx file like this:
"# 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函数进行发送才能实现?
How do I get the returned struct into my Python? Is this kind of thing only possible by creating a struct in the Cython and sending by reference to a void c function?
作为参考,我的setup.py是:
As a reference, my setup.py is:
from distutils.core import setup, Extension
from Cython.Build import cythonize
setup(ext_modules = cythonize(
"point.pyx",
language="c"
)
)
推荐答案
通常,您通常会编写某种包含c级结构的包装器类,例如:
Most typically you would write some kind of wrapper class that holds the c-level struct, for example:
# point.pyx
cdef extern from "pointc.c":
ctypedef struct Point:
int x
int y
Point make_and_send_point(int x, int y)
cdef class PyPoint:
cdef Point p
def __init__(self, x, y):
self.p = make_and_send_point(x, y)
@property
def x(self):
return self.p.x
@property
def y(self):
return self.p.y
使用情况
>>> import point
>>> p = point.PyPoint(10, 10)
>>> p.x
10
这篇关于使用Cython将结构从C返回到Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文