微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决如何在 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 举报,一经查实,本站将立刻删除。