如何在 python 和 C++ 之间传递和返回 numpy 数组?

问题描述

我有一些关于 python c 扩展的问题。 我想将 ndarray 从 python 传递到 C++,做一些工作来改变这个 ndarray 中的值,然后返回到 python 代码(然后我将在 python 中使用'a'做一些更多的工作)。 我使用 windows 10 64 位,python 3.7.6 32 位,visual studio 2019。

在这里我附上了我的代码的一部分,但它只能工作一次,即使有一个 for 循环来运行 cfunc n 次。返回值也有一些问题(我不知道确切,我无法看到或绘制返回的数组。)

import cModule

for i in range(0,n):
 print(a[i]) # it works only once and doesn't do anything in the second loop. It just become silent and finished the code without any error nor warning message.
 some_value,a = cModule.cfunc(a,...)
#include <Python.h>
#include <numpy\ndarraytypes.h>
#include <numpy\ndarrayobject.h>
#include <numpy\arrayobject.h>

int cfunc(double* a,...)
{
... // Do some job to change a
}

static PyObject* cfunc_translate(PyObject* self,PyObject* args)
{
PyArrayObject* a_py;
double* a;

if (!PyArg_ParseTuple(args,"O",&a))
 return NULL;
}

a = (double*)a_py->data;

int length_a = 512*512;

int some_value = cfunc(a);

npy_intp dims[1];
dims[0] = 1;
PyObject* a_return = PyArray_SimpleNewFromData(length_a,dims,NPY_DOUBLE,a); // This part doesn't work from the 2nd loop in the python code. Or if I try to see the elements in 'a',it just become silent and finished the code without any error nor warning message.

free(a);
Py_XDECREF(a_py);

return Py_BuildValue("iO",some_value,a_return);

当我返回值时,'a' 可能会以某种方式扭曲。但我不知道如何解决这个问题。 (返回的 a 也是 ndarray。) 如果您有任何想法或需要更多信息,请告诉我。

非常感谢!

最好的祝福, 耶苏

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)