繁体   English   中英

使用Cython将结构从C返回到Python

[英]Return a struct from C to Python using Cython

我试图从ac文件中将结构传回我的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"
     )
)

通常,您会编写某种包含c级结构的包装类,例如:

# 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的默认行为是将它转换为Python字典,这对你来说可能已经足够了。 (这仅适用于由简单类型组成的结构)。

有几个原因导致这种情况无效。 首先,您应该从头文件中执行cdef extern from ,而不是源文件,否则会出现有关多个定义的错误(我认为这只是创建最小示例时的错误)。 其次,您需要在您的cdef extern块中放置Point的定义:

cdef extern from "pointc.h":
    cdef struct Point:
        int x
        int y

如果你不这样做,那么Cython会为你的struct( __pyx_t_5point_Point )创建一个错误的内部名称,它与C函数签名不匹配,因此失败。

通过此更正,您将获得将结构转换为dicts的正确默认行为。 (这应该是双向的 - 你可以将dicts转换回结构)。 如果这不是您想要的,请关注@ chrisb的答案

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM