【发布时间】:2021-06-08 02:51:03
【问题描述】:
我想从 c++ 返回数组并在 python 代码中将其作为 numpy 数组接收。 我使用了 PyArray_SimpleNewFromData 和 Py_BuildValue 但我的程序只是退出了,没有任何错误/警告消息应该运行“PyArray_SimpleNewFromData”,所以很难理解是什么问题。
这是我返回数组的代码的一部分。
#include <Python.h>
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
#include "numpy\ndarraytypes.h"
#include "numpy\ndarrayobject.h"
#include "numpy\arrayobject.h"
static PyObject* cfunc(PyObject* self, PyObject* args)
{
PyArrayObject* arr;
double* carr;
if (!PyArg_ParseTuple(args, "O", &arr))
{
return NULL;
}
carr = (double*)PyArray_DATA(arr);
...// do some job here to change the values of carr elements.
npy_intp dims[1];
dims[0] = 1; // Will be a 1D numpy array
int length_arr = 512 * 512;
PyObject* arr_return = PyArray_SimpleNewFromData(length_arr, dims, NPY_DOUBLE,
(void*)carr);
return Py_BuildValue("O", arr_return); // Python code will receive the array as numpy array.
}
如果您有任何想法或需要更多信息,请告诉我。
【问题讨论】:
标签: python c++ arrays numpy numpy-ndarray