gpt4 book ai didi

python - 如何将 C 数组返回给 Python?

转载 作者:太空宇宙 更新时间:2023-11-04 01:14:36 25 4
gpt4 key购买 nike

我写了一个由 Python 调用的 Python/C 扩展函数,如何将二维数组 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);
}

最佳答案

您使用的是哪种阵列?我觉得方便的一种方法是使用 numpy 数组,并就地修改数据。 Numpy 已经有很多用于操作整数数组的出色操作,因此如果您尝试添加一些额外的功能,这会很方便。

第 1 步:将您的 C 扩展链接到 numpy

在 Windows 上,这类似于

#include "C:\Python34/Lib/site-packages/numpy/core/include/numpy/arrayobject.h"

在 osx 上是这样的

#include "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/numpy/core/include/numpy/arrayobject.h"

第 2 步:获取指向数据的指针。这非常简单

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 中的二维 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 数组将具有更改后的值。

关于python - 如何将 C 数组返回给 Python?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25459479/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com