繁体   English   中英

从 c++ 到 python 返回数组

[英]Return array from c++ to python

我想从 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.
}

如果您有任何想法或需要更多信息,请告诉我。

阅读文档(强调我的):

PyObject* PyArray_SimpleNewFromData(int nd, npy_intp const* dims, int typenum, void* data)

围绕给定指针指向的数据创建一个数组包装器。 数组标志将默认数据区域行为良好且 C 样式连续。 数组的形状由长度为 nd 的 dims c 数组给出。 数组的数据类型由 typenum 表示。 If data comes from another reference-counted Python object, the reference count on this object should be increased after the pointer is passed in, and the base member of the returned ndarray should point to the Python object that owns the data. 这将确保提供的 memory 在返回的数组存在时不会被释放。 要在释放 ndarray 后立即释放 memory,请在返回的 ndarray 上设置 OWNDATA 标志。

第一个参数nd (在您的情况下为length_arr )是维度数,因此 function 将知道第二个参数dims的条目数(大多数 C 函数希望告诉 ZA3CBC3F9D0CE2F2C1DCE 的长度传递给它们,除非它们被终止,除非它们被终止不知何故,例如 null 终止的字符数组/字符串)。 认为dimsarr.shape ,而ndlen(arr.shape) (维数)。

在您的情况下, dims[0]应该是512 * 512并且length_arr应该是1 你有它相反的方式。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM