使用cython将numpy数组列表传递给C.

rwo*_*lst 5 c python numpy cython

我有一个list_of_arrays3D numpy数组列表,我想用模板传递给C函数

int my_func_c(double **data, int **shape, int n_arrays)
Run Code Online (Sandbox Code Playgroud)

这样的

data[i]  : pointer to the numpy array values in list_of_arrays[i]
shape[i] : pointer to the shape of the array in list_of_arrays[i] e.g. [2,3,4]
Run Code Online (Sandbox Code Playgroud)

如何my_func_c使用cython接口函数调用?

我的第一个想法是做类似下面的事情(有效),但我觉得有一个更好的方法就是使用numpy数组而不需要mallocing和freeing.

# my_func_c.pyx

import numpy as np
cimport numpy as np
cimport cython
from libc.stdlib cimport malloc, free

cdef extern from "my_func.c":
    double my_func_c(double **data, int **shape, int n_arrays)

def my_func(list list_of_arrays):
    cdef int n_arrays  = len(list_of_arrays)
    cdef double **data = <double **> malloc(n_arrays*sizeof(double *))
    cdef int **shape   = <int **> malloc(n_arrays*sizeof(int *))
    cdef double x;

    cdef np.ndarray[double, ndim=3, mode="c"] temp

    for i in range(n_arrays):
        temp = list_of_arrays[i]
        data[i]  = &temp[0,0,0]
        shape[i] = <int *> malloc(3*sizeof(int))
        for j in range(3):
            shape[i][j] = list_of_arrays[i].shape[j]

    x = my_func_c(data, shape, n_arrays)

    # Free memory
    for i in range(n_arrays):
        free(shape[i])
    free(data)
    free(shape)

    return x
Run Code Online (Sandbox Code Playgroud)

NB

要查看一个工作示例,我们可以使用一个非常简单的函数来计算列表中所有数组的乘积.

# my_func.c

double my_func_c(double **data, int **shape, int n_arrays) {
    int array_idx, i0, i1, i2;

    double prod = 1.0;

    // Loop over all arrays
    for (array_idx=0; array_idx<n_arrays; array_idx++) {
        for (i0=0; i0<shape[array_idx][0]; i0++) {
            for (i1=0; i1<shape[array_idx][1]; i1++) {
                for (i2=0; i2<shape[array_idx][2]; i2++) {
                    prod = prod*data[array_idx][i0*shape[array_idx][1]*shape[array_idx][2] + i1*shape[array_idx][2] + i2];
                }
            }
        }
    }

    return prod;
}
Run Code Online (Sandbox Code Playgroud)

创建setup.py文件,

# setup.py

from distutils.core import setup
from Cython.Build import cythonize
import numpy as np

setup(
    name='my_func',
    ext_modules = cythonize("my_func_c.pyx"),
    include_dirs=[np.get_include()]
    )
Run Code Online (Sandbox Code Playgroud)

python3 setup.py build_ext --inplace
Run Code Online (Sandbox Code Playgroud)

最后我们可以进行一个简单的测试

# test.py

import numpy as np
from my_func_c import my_func

a = [1+np.random.rand(3,1,2), 1+np.random.rand(4,5,2), 1+np.random.rand(1,2,3)]

print('Numpy product: {}'.format(np.prod([i.prod() for i in a])))
print('my_func product: {}'.format(my_func(a)))
Run Code Online (Sandbox Code Playgroud)

运用

python3 test.py
Run Code Online (Sandbox Code Playgroud)

Dav*_*idW 5

一种替代方法是让 numpy 为您管理内存。您可以通过使用 numpy 数组来做到这一点,np.uintp该数组是一个与任何指针大小相同的无符号整数。

不幸的是,这确实需要一些类型转换(在“指针大小的 int”和指针之间),这是隐藏逻辑错误的好方法,所以我对此不是 100% 满意。

def my_func(list list_of_arrays):
    cdef int n_arrays  = len(list_of_arrays)
    cdef np.uintp_t[::1] data = np.array((n_arrays,),dtype=np.uintp)
    cdef np.uintp_t[::1] shape = np.array((n_arrays,),dtype=np.uintp)
    cdef double x;

    cdef np.ndarray[double, ndim=3, mode="c"] temp

    for i in range(n_arrays):
        temp = list_of_arrays[i]
        data[i]  = <np.uintp_t>&temp[0,0,0]
        shape[i] = <np.uintp_t>&(temp.shape[0])

    x = my_func_c(<double**>(&data[0]), <np.intp_t**>&shape[0], n_arrays)
Run Code Online (Sandbox Code Playgroud)

(我应该指出,我只是确认它可以编译并没有进一步测试它,但基本思想应该没问题)


您这样做的方式可能是一种非常明智的方式。对应该有效的原始代码进行了一点点简化

shape[i] = <np.uintp_t>&(temp.shape[0])
Run Code Online (Sandbox Code Playgroud)

而不是malloc和 复制。我还建议将frees 放在一个finally块中以确保它们能够运行。


编辑: @ead 有用地指出numpy 形状存储为np.intp_t- 即一个足够大以容纳指针的有符号整数,大部分是 64 位 - 而int通常是 32 位。因此,要传递形状而不复制,您需要更改 C api。强制转换帮助使该错误更难被发现(“隐藏逻辑错误的好方法”)