簡體   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