如何访问通过Cython传递的numpy数组

时间:2014-07-21 12:04:31

标签: python c arrays numpy cython

我试图了解哪种是最快最安全方式来访问通过Cython传递给C代码的NumPy数组。 我有以下文件:

func.c:

typedef struct {
    int nr;                
    double *my_array;      
} my_struct;

my_struct grid;

void allocate(int n) {
    grid.nr = n;
    grid.my_array = (double*)malloc(grid.nr*sizeof(double));
}

void Cfunc1(double *array) {
    my_array = array;

    //e.g. operation on my_array..
    for (int i=0; i<n; i++) my_array[i] *= 0.1;
}

void Cfunc2(int n, double *array) {
    for (int i=0; i<n; i++) {
        my_array[i] = array[i];

    //e.g. operation on my_array..
    for (int i=0; i<n; i++) my_array[i] *= 0.1;

}

func_wrap.pyx:

cdef extern from "func.h":
    void myfunc1(double *)
    void myfunc2(int, double *) 
    void allocate(int)

def pyfunc1(int n, double[:] array):
    allocate(n)
    Cfunc1(&array[0])

def pyfunc2(int n, double[:] array):
    allocate(n)
    Cfunc2(n, &array[0])

setup.py:

from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
import distutils
setup(cmdclass = {'build_ext': build_ext}, ext_modules = [Extension("func", ["func.c"])]) 
生成

func.so

python setup.py build_ext --inplace

py_func.py:

import numpy
import func

arr = numpy.random.randn(10)
func.pyfunc1(arr)   # or func.pyfunc2(len(arr), arr)

有些问题:

  1. 使用Cfunc1()Cfunc2()会更快吗?

  2. 使用Cfunc2意味着数据被复制了?你会使用哪一个?

  3. 从理论上讲,我会说Cfunc1不需要先前malloc my_array,而Cfunc2则需要它。相反,这些功能似乎在没有malloc的情况下工作,你能告诉我为什么吗?

  4. 非常感谢!

1 个答案:

答案 0 :(得分:0)

你的问题归结为“当我将数组传递给C代码时,我是否需要复制数组的内容”。答案是不,你不是,但在某些情况下你可能想要。主要是当你想以某种方式修改内容而不破坏原始数组。此外,在某些情况下,在对数据运行计算密集型算法之前,将非可重复数组复制到连续数组可能很有用。话虽如此,您当前的代码假定数据已经是连续的,因此在非连续的情况下,它只会给出错误的结果,复制或不复制。

如果您要对numpy数组使用指针访问,那么您几乎总是希望使用double[::1]而不是double[:],以便cython插入错误检查步骤以确保数组是连续的。

此外,如果您要将numpy数组的内容复制到其他数据结构(即c数组或malloc内存块)中,则需要声明/分配足够的内存才能执行此操作。在没有看到如何声明和分配my_array的情况下,无法知道代码是如何工作的,但是必须在某处分配内存。