c++ - 如何将 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;
}
如何打印数组的正确值?
解决方案
推荐阅读
- python - File not saving django
- botframework - Try to connect locally to Chatbot but get unauthorized error
- javascript - Angular 8 Initialized Member Array is Undefined
- r - Pad within grouped dates in R
- javascript - 如何提交表单数据到快递服务器?
- reactjs - 测试时调用 onChange 方法后 DatePicker 组件中的日期未更新
- php - How do you create ManyToOne relation within single supermapped class
- python - 为什么在 Pandas 中使用方括号?
- javascript - 试图建立一个宾果游戏,而循环无限,似乎无法找到原因
- sql - 检查用户输入到 ASP.net webform 文本框的 SQL 列中是否存在