2017-09-29 248 views
1

我想在我的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)在C++中嵌入python/numpy

虽然从代码审查职位的例子基本上工作,我遇到了返回值时,我修改了Python和C + +脚本的麻烦:当我试图返回一个在python中创建的变量结果是而不是预期的计算。 我的猜测是该对象以某种方式超出了范围,但我无法解决这个问题。

我用下面的python脚本在一个名为mymodule.py文件:

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一个警告罚款())。我瞄准蟒蛇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 

这是最后的输出,让我的麻烦,其中蟒蛇返回numpy的阵列中的第一行设置在python脚本中。 从python打印语句看来,numpy数组很好(不是nan),但是一旦它被引用到C++中,事物就会横向移动。

如果我取消array_tutorial函数中return语句上面的两行的注释,那么第一个函数调用的结果会相同(令人失望)。

因此,我的问题是如何在C++中获得正确的值,而不会导致对象超出范围?

我对这篇冗长的文章表示歉意,并且预先感谢您的帮助!


编辑:正如指出的那样,在Python中numpy的阵列下面lomereiter应建立保持数据类型的初衷。 这解决了这个问题。 更好的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 
+0

我得到这个错误'''main.cpp:26:21:error:expected';'声明结束 npy_intp dims [2] {SIZE,SIZE};''' – sAguinaga

回答

1

当您创建Python代码数组应指定D型。您在C++代码中使用long double,而dtype被推断为int64(在64位平台上)

+0

非常感谢 - 确实解决了它。正确的dtype是“numpy.float128”(在我的情况下) – user3456032