gpt4 book ai didi

python - 将 numpy-C 数组转换为 C double* [] 并返回

转载 作者:行者123 更新时间:2023-11-30 16:53:21 27 4
gpt4 key购买 nike

经过长时间的努力,我成功地将 numpy 数组导入到 C 中,并返回一个具有相同大小的空 numpy 数组。现在我想使用给定的 3x3 内核执行卷积。我习惯于创建第二个执行操作的 C 函数,而 python 中的可调用函数只是转换输入参数以将它们传递给函数。所以我想做的是:

  1. 从 python 接收 numpy 数组
  2. 将其转换为 C-double 数组
  3. 执行卷积(暂时交给我)
  4. 将卷积数组转换回 C-numpy 数组
  5. 将 C-numpy 数组返回给 python。

所以步骤 1 和 5 已经完成。代码:

static PyObject *CPtest_convolute(PyObject *self, PyObject *args)
{
PyArrayObject *in_array;
PyObject *out_array;

/*extract input array, create output array*/
if (!PyArg_ParseTuple(args, "O!", &PyArray_Type, &in_array)) return NULL;

/*convert numpy to double*[]*/
/*convArr = convolute(in_array, kernel);*/

out_array = PyArray_NewLikeArray(in_array, NPY_ANYORDER, NULL, 0);
if (out_array == NULL)
/*for now, i am not going to throw an error, instead return 0.
python can use that 0 to throw the error */
return Py_BuildValue("i", 0);

/*convert convArr to out_array*/

return out_array;
};

进一步说明,我在 Windows 8 上使用 Python 2.7。PyMODINIT_FUNC 和 PyMethodDef 已正确初始化(这意味着没有错误且结果正确)。虽然我找到了多个结果,但它们都使用了 ctypes 或 SWIG 之类的东西,而不是 C。虽然我对 C 有点陌生,但我熟悉基础知识(来自 Arduino C)。

提前致谢!

最佳答案

通常你可以通过调用(在Python中)从numpy数组获取指针:

arr.__array_interface__['data']

不过,请注意冲突。

给定一个c缓冲区,您可以通过numpy.frombuffer函数构造numpy数组:

arr = numpy.frombuffer(buf, dtype, size, offset=0)

(我假设您通过 python 或其 C API 创建新的读写缓冲区,然后使用它来存储计算结果)

关于python - 将 numpy-C 数组转换为 C double* [] 并返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40884508/

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