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

如何从 Python 中导入 numoy ndarray 返回到 C++嵌入

如何解决如何从 Python 中导入 numoy ndarray 返回到 C++嵌入

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

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

当我在 Return ndarray from Python-extension to C 问题中使用解决方案时,CPP 输出

nan nan nan nan

python 代码

#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;

}

如何打印数组的正确值?

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。