【发布时间】:2018-03-28 15:54:32
【问题描述】:
我想在python 中使用由c 函数创建的二维数组。我在today 之前询问了如何做到这一点,@Abhijit Pritam 建议的一种方法是使用结构。我实现了它并且它确实有效。
c 代码:
typedef struct {
int arr[3][5];
} Array;
Array make_array_struct() {
Array my_array;
int count = 0;
for (int i = 0; i < 3; i++)
for (int j = 0; j < 5; j++)
my_array.arr[i][j] = ++count;
return my_array;
}
在 python 中我有这个:
cdef extern from "numpy_fun.h":
ctypedef struct Array:
int[3][5] arr
cdef Array make_array_struct()
def make_array():
cdef Array arr = make_array_struct()
return arr
my_arr = make_array()
my_arr['arr']
[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15]]
但是有人建议这不是解决问题的最佳方法,因为可以让 python 控制数据。我正在尝试实现这一点,但到目前为止我还没有做到这一点。这就是我所拥有的。
c 代码:
int **make_array_ptr() {
int **my_array = (int **)malloc(3 * sizeof(int *));
my_array[0] = calloc(3 * 5, sizeof(int));
for (int i = 1; i < 3; i++)
my_array[i] = my_array[0] + i * 5;
int count = 0;
for (int i = 0; i < 3; i++)
for (int j = 0; j < 5; j++)
my_array[i][j] = ++count;
return my_array;
}
蟒蛇:
import numpy as np
cimport numpy as np
np.import_array()
ctypedef np.int32_t DTYPE_t
cdef extern from "numpy/arrayobject.h":
void PyArray_ENABLEFLAGS(np.ndarray arr, int flags)
cdef extern from "numpy_fun.h":
cdef int **make_array_ptr()
def make_array():
cdef int[::1] dims = np.array([3, 5], dtype=np.int32)
cdef DTYPE_t **data = <DTYPE_t **>make_array_ptr()
cdef np.ndarray[DTYPE_t, ndim=2] my_array = np.PyArray_SimpleNewFromData(2, &dims[0], np.NPY_INT32, data)
PyArray_ENABLEFLAGS(my_array, np.NPY_OWNDATA)
return my_array
我正在关注Force NumPy ndarray to take ownership of its memory in Cython
,这似乎是我需要做的。在我的情况下它是不同的,因为我需要二维数组,所以我可能不得不做一些不同的事情,因为例如函数期望data 是一个指向 int 的指针,我给了它一个指向 int 指针的指针。
我需要做什么才能使用这种方法?
【问题讨论】: