首页 > 解决方案 > 如何将 numoy ndarray 从 Python 返回到 C++(嵌入)

问题描述

我有一个 Python 函数,它将图像的 x,y 坐标返回为 numpy ndarray

#python output
type<np ndarray>
[100, 200]
[200, 300]
[300, 400]
[400, 500]

当我使用从 Python-extension 到 C 的 Return ndarray中的解决方案时,CPP 输出

nan nan nan nan

蟒蛇代码

#python code
def main_py
...
...
...
    print (x[0])
    print (type(x))
    return

cpp代码

//CPP code
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
#include "Python.h"
#include "numpy/arrayobject.h"
#include<iostream>
#include<string.h>

using namespace std;

int main()
{
Py_Initialize();

PyRun_SimpleString
(
    "import os, sys \n"
    "sys.path.append(os.getcwd()) \n"
);
import_array()

PyObject *pName, *pArgs, *pReturn, *pModule, *pFunc;
PyArrayObject *np_ret, *np_arg;
const int SIZE{ 10 };
npy_intp dims[2]{SIZE, SIZE};
const int ND{ 2 };
long double(*c_arr)[SIZE]{ new long double[SIZE][SIZE] };
long double* c_out;

pName = PyUnicode_FromString("pythonscript");     
pModule = PyImport_Import(pName);
pFunc = PyObject_GetAttrString(pModule, "main_py");
pArgs = PyTuple_Pack(2, PyUnicode_FromString("xyz"));
pReturn = PyObject_CallObject(pFunc, pArgs);

np_ret = reinterpret_cast<PyArrayObject*>(pReturn);
int len{ PyArray_SHAPE(np_ret)[0] };
c_out = reinterpret_cast<long double*>(PyArray_DATA(np_ret));
cout << "Printing output array" << endl;
for (int i{}; i < len; i++)
    cout << c_out[i] << ' ';
cout << endl;

Py_Finalize();
return 0;

}

如何打印数组的正确值?

标签: c++python-3.xpointersnumpy-ndarraypython-embedding

解决方案


推荐阅读