如何将C数组返回给Python?
我写了一个Python/C扩展函数,这个函数是被Python调用的。请问我该如何将一个二维数组 int[][] 返回给Python呢?
static PyObject* inference_function(PyObject *self, PyObject *args)
{
PyObject* doc_lst;
int K,V;
double alpha,beta;
int n_iter;
if (!PyArg_ParseTuple(args, "Oiiddi", &doc_lst, &K,&V, &alpha,&beta,&n_iter))
{
printf("传入参数错误!\n");
return NULL;
}
return Py_BuildValue("i", 1);
}
1 个回答
3
你在使用什么样的数组呢?我觉得用numpy数组挺方便的,可以直接在原地修改数据。因为numpy已经有很多很棒的操作,可以用来处理整数数组,所以如果你想增加一些额外的功能,这样做会很方便。
第一步:把你的C扩展和numpy连接起来
在Windows上,这样做:
#include "C:\Python34/Lib/site-packages/numpy/core/include/numpy/arrayobject.h"
在Mac上,做法是这样的:
#include "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/numpy/core/include/numpy/arrayobject.h"
第二步:获取数据的指针。 这其实很简单。
int* my_data_to_modify;
if (PyArg_ParseTuple(args, "O", &numpy_tmp_array)){
/* Point our data to the data in the numpy pixel array */
my_data_to_modify = (int*) numpy_tmp_array->data;
}
... /* do interesting things with your data */
在C中使用2D numpy数组
当你用这种方式处理数据时,可以把它分配为一个二维数组,比如:
np.random.randint( 0, 100, (100,2) )
或者如果你想要一个空白的数组,可以全填零。
但C只关心连续的数据,这意味着你可以通过“行”的长度来循环遍历它,并像对待二维数组一样修改它。
举个例子,如果你传入的是RGB颜色,比如一个100x3的数组,你可以考虑:
int num_colors = numpy_tmp_array2->dimensions[0]; /* This gives you the column length */
int band_size = numpy_tmp_array2->dimensions[1]; /* This gives you the row length */
for ( i=0; i < num_colors * band_size; i += band_size ){
r = my_data[i];
g = my_data[i+1];
b = my_data[i+2];
}
要在原地修改数据,只需改变数据数组中的一个值。在Python那边,numpy数组会显示出修改后的值。