我正在尝试在我的C++应用程序中使用Python 3(带有numpy)。这意味着需要将C ++数组发送到Python进行计算,然后在C ++中检索结果。为此,我参考了这里讨论的代码:
https://codereview.stackexchange.com/questions/92266/sending-a-c-array-to-python-numpy-and-back/92353#92353
以及这里:
Sending a C++ array to Python and back (Extending C++ with Numpy)。
虽然代码审查帖子中的示例基本上可以工作,但是当我修改Python和C++脚本时,返回值存在问题:当我尝试返回在Python中创建的变量时,结果是一组nan向量而不是预期的计算结果。我的猜测是对象某种程度上超出了作用域,但我无法解决这个问题。
我在名为mymodule.py的文件中使用以下Python脚本:
与被接受的答案相比,我不得不添加以下内容。
为了确保 Python 脚本被找到,我添加了第二个函数调用,调用的是名为 "myfunction" 的函数,该函数没有输入参数,并删除了部分错误处理。
我使用的是 Ubuntu 16.10。
虽然代码审查帖子中的示例基本上可以工作,但是当我修改Python和C++脚本时,返回值存在问题:当我尝试返回在Python中创建的变量时,结果是一组nan向量而不是预期的计算结果。我的猜测是对象某种程度上超出了作用域,但我无法解决这个问题。
我在名为mymodule.py的文件中使用以下Python脚本:
import numpy
def array_tutorial(a):
print("array_tutorial - python")
print(a)
print("")
firstRow = a[0,:]
#beta = numpy.array([[10,20,30],[10,20,30],[10,20,30]])
#firstRow = beta[0,:]
return firstRow
def myfunction():
beta = numpy.array([[1,2,3],[1,2,3],[1,2,3]])
print("myfunction - python")
print(beta)
print("")
firstRow = beta[0,:]
return firstRow
我的C++代码在文件numpy_cpp.cpp中,这是接受代码审查帖子的答案的略有改动和简化版。
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
#include <stdio.h>
#include <iostream>
#include <stdlib.h>
#include <Python.h>
#include "numpy/arrayobject.h"
int main(int argc, char* argv[])
{
setenv("PYTHONPATH", ".", 0);
Py_Initialize();
import_array();
// Build the 2D array in C++
const int SIZE = 3;
npy_intp dims[2]{SIZE, SIZE};
const int ND = 2;
long double(*c_arr)[SIZE]{ new long double[SIZE][SIZE] };
for (int i = 0; i < SIZE; i++){
for (int j = 0; j < SIZE; j++){
c_arr[i][j] = i + j;}
}
// Convert it to a NumPy array.
PyObject *pArray = PyArray_SimpleNewFromData(ND, dims, NPY_LONGDOUBLE, reinterpret_cast<void*>(c_arr));
// import mymodule
const char *module_name = "mymodule";
PyObject *pName = PyUnicode_FromString(module_name);
PyObject *pModule = PyImport_Import(pName);
Py_DECREF(pName);
// import function
const char *func_name = "array_tutorial";
PyObject *pFunc = PyObject_GetAttrString(pModule, func_name);
PyObject *pReturn = PyObject_CallFunctionObjArgs(pFunc, pArray, NULL);
PyArrayObject *np_ret = reinterpret_cast<PyArrayObject*>(pReturn);
// Convert back to C++ array and print.
int len = PyArray_SHAPE(np_ret)[0];
long double* c_out;
c_out = reinterpret_cast<long double*>(PyArray_DATA(np_ret));
std::cout << "Printing output array - C++" << std::endl;
for (int i = 0; i < len; i++){
std::cout << c_out[i] << ' ';
}
std::cout << std::endl << std::endl;
// import function without arguments
const char *func_name2 = "myfunction";
PyObject *pFunc2 = PyObject_GetAttrString(pModule, func_name2);
PyObject *pReturn2 = PyObject_CallFunctionObjArgs(pFunc2, NULL);
PyArrayObject *np_ret2 = reinterpret_cast<PyArrayObject*>(pReturn2);
// convert back to C++ array and print
int len2 = PyArray_SHAPE(np_ret2)[0];
long double* c_out2;
c_out2 = reinterpret_cast<long double*>(PyArray_DATA(np_ret2));
std::cout << "Printing output array 2 - C++" << std::endl;
for (int i = 0; i < len2; i++){
std::cout << c_out2[i] << ' ';
}
std::cout << std::endl << std::endl;
Py_Finalize();
return 0;
}
与被接受的答案相比,我不得不添加以下内容。
setenv("PYTHONPATH", ".", 0);
为了确保 Python 脚本被找到,我添加了第二个函数调用,调用的是名为 "myfunction" 的函数,该函数没有输入参数,并删除了部分错误处理。
我使用的是 Ubuntu 16.10。
g++ -Wall numpy_cpp.cpp -I/usr/include/python3.5m/ -lpython3.5m
为了编译和链接代码(这部分进展顺利,除了 import_array() 函数产生的一个警告),我正在使用 Python 3。
但运行程序时,控制台输出以下内容:
array_tutorial - python
[[ 0.0 1.0 2.0]
[ 1.0 2.0 3.0]
[ 2.0 3.0 4.0]]
Printing output array - C++
0 1 2
myfunction - python
[[1 2 3]
[1 2 3]
[1 2 3]]
Printing output array 2 - C++
nan nan nan
最后一个输出让我感到困扰,其中Python返回了在Python脚本中设置的numpy数组的第一行。从Python打印语句来看,numpy数组很好(不是nan),但是一旦它被引用到C++中,事情就变得复杂起来。
如果我取消注释array_tutorial函数中返回语句上面的两行,我将获得相同(令人失望)的结果,即第一个函数调用。
因此,我的问题是如何在C++中获取正确的值,而不使对象(可能)超出范围?
对于冗长的帖子,我表示歉意,并提前感谢任何帮助!
编辑:正如lomereiter在下面指出的那样,Python中的numpy数组应该考虑到数据类型进行设置。这解决了问题。更好的Python脚本输出接收到的数组的数据类型并指定声明数组的数据类型:
import numpy
def array_tutorial(a):
print("array_tutorial - python")
print(a)
print(numpy.dtype(a[0,0]))
print("")
firstRow = a[0,:]
#beta = numpy.array([[10,20,30],[10,20,30],[10,20,30]],dtype=numpy.float128)
#firstRow = beta[0,:]
return firstRow
def myfunction():
beta = numpy.array([[1,2,3],[1,2,3],[1,2,3]],dtype=numpy.float128)
print("myfunction - python")
print(beta)
print("")
firstRow = beta[0,:]
return firstRow
main.cpp:26:21: error: expected ';' at end of declaration npy_intp dims[2]{SIZE, SIZE};
- sAguinaga