传递numpy的阵列到C code包裹着用Cython [英] Passing Numpy arrays to C code wrapped with Cython

查看:282
本文介绍了传递numpy的阵列到C code包裹着用Cython的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已有C code小一点,我想用用Cython包装。我希望能够建立一个数numpy的数组,然后通过这些数组作为参数到C code,其功能拍摄标准的C数组(1D和2D)。我搞清楚怎么写正确的.pyx code,妥善处理事情方面我有点卡住了。

I have a small bit of existing C code that I want to wrap using Cython. I want to be able to set up a number of numpy arrays, and then pass those arrays as arguments to the C code whose functions take standard c arrays (1d and 2d). I'm a little stuck in terms of figuring out how to write the proper .pyx code to properly handle things.

有少数的函数,而是在文件funcs.h一个典型的函数看起来是这样的:

There are a handful of functions, but a typical function in the file funcs.h looks something like:

double InnerProduct(double *A, double **coords1, double **coords2, const int len)

然后我有一个具有相应的行.pyx文件:

I then have a .pyx file that has a corresponding line:

cdef extern from "funcs.h":
    double InnerProduct(double *A, double **coords1, double **coords2, int len)

在这里我终于摆脱了的常量的,因为用Cython不支持它。凡我被困然后包装code应该看起来像一个M×N个numpy的数组传递给** coords1和** coords2争论什么。

where I got rid of the const because cython doesn't support it. Where I'm stuck is what the wrapper code should then look like to pass a MxN numpy array to the **coords1 and **coords2 arguments.

我一直在努力寻找正确的文档或教程这种类型的问题。任何建议将是最AP preciated。

I've struggled to find the correct documentation or tutorials for this type of problem. Any suggestions would be most appreciated.

推荐答案

您可能想用Cython的输入memoryviews功能,您可以在全血淋淋的细节的此处。这基本上是与numpy的或其他阵列的工作的更新,更统一的方式。这些都可以在Python土地公开为numpy的阵列,也可以将它们导出到Python(例如,的这里)。你必须要注意的是如何跨越工程,并确保你即将例如一致C-连续与FORTRAN般的阵列,但该文档是pretty如何做到这一点清楚了。

You probably want Cython's "typed memoryviews" feature, which you can read about in full gory detail here. This is basically the newer, more unified way to work with numpy or other arrays. These can be exposed in Python-land as numpy arrays, or you can export them to Python (for example, here). You have to pay attention to how the striding works and make sure you're consistent about e.g. C-contiguous vs. FORTRAN-like arrays, but the docs are pretty clear on how to do that.

不知道更多一点关于你的函数很难上正是这样做的最好办法更具体的 - 即是只读的C函数的阵列? (我想是根据您所提供的签名,但我不是100%确定)。如果是这样,你不必担心,如果需要获得C-个州进行复印,因为C函数不需要说话回到Python的水平numpy的数组。但类型memoryviews会让你做任何这以最简单的。

Without knowing a bit more about your function it's hard to be more concrete on exactly the best way to do this - i.e., is the C function read-only for the arrays? (I think yes based on the signature you gave, but am not 100% sure.) If so you don't need to worry about making copies if needed to get C-contiguous states, because the C function doesn't need to talk back to the Python-level numpy array. But typed memoryviews will let you do any of this with a minimum of fuss.

这篇关于传递numpy的阵列到C code包裹着用Cython的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆