如何将数组从c ++传递给python函数并将python返回的数组检索到c ++

时间:2012-03-29 09:40:49

标签: c++ python c numpy

我正在编写一个c ++程序来调用python函数并检索返回数组。但是我总是得到如下错误:

  

只能将length-1数组转换为Python标量

和我的c ++代码:

 int main(int argc, char *argv[])
{
    int i;
    PyObject *pName, *pModule, *pDict, *pFunc, *pArgs, *pValue;

    if (argc < 3) 
    {
        printf("Usage: exe_name python_source function_name\n");
        return 1;
    }

    // Initialize the Python Interpreter
    Py_Initialize();

    // Build the name object
    pName = PyString_FromString(argv[1]);

    // Load the module object
    pModule = PyImport_Import(pName);

    // pDict is a borrowed reference 
    pDict = PyModule_GetDict(pModule);

    // pFunc is also a borrowed reference 
    pFunc = PyDict_GetItemString(pDict, argv[2]);

    if (PyCallable_Check(pFunc)) 
    {
        // Prepare the argument list for the call
        if( argc > 3 )
        {
                pArgs = PyTuple_New(argc - 3);
                for (i = 0; i < argc - 3; i++)
                {
                    pValue = PyInt_FromLong(atoi(argv[i + 3]));
                    if (!pValue)
                    {
                        PyErr_Print();
                        return 1;
                    }
                    PyTuple_SetItem(pArgs, i, pValue);  
                }

                pValue = PyObject_CallObject(pFunc, pArgs);

                if (pArgs != NULL)
                {
                    Py_DECREF(pArgs);
                }
        } else
        {
                pValue = PyObject_CallObject(pFunc, NULL);
        }

        if (pValue != NULL) 
        {
            cout <<pValue;
            printf("Return of call : %ld\n", PyInt_AsLong(pValue));
            PyErr_Print();
            Py_DECREF(pValue);
        }
        else 
        {
            PyErr_Print();
        }
    } else 
    {
        PyErr_Print();
    }

    // Clean up
    Py_DECREF(pModule);
    Py_DECREF(pName);

    // Finish the Python Interpreter
    Py_Finalize();

    system("PAUSE");
    return 0;
}

Python函数:

 import numpy as np
    _ZERO_THRESHOLD = 1e-9      # Everything below this is zero
def data():
    print "process starting..."
    N = 5
    obs = np.matrix([np.random.normal(size=5) for _ in xrange(N)])              
    V = pca_svd(obs)
    print "V:"
    print V[0:5]

    pca = IPCA(obs.shape[1], 3)
    for i in xrange(obs.shape[0]):
        x = obs[i,:].transpose()
        print " "
        print "new input:"
        print x
        pca.update(x)

    U = pca.components
    A = pca.variances
    B = U.T*x
    print B
    return B

我知道这句话有问题

  

PyInt_AsLong(p值)   任何人都可以告诉我如何解决这个问题,以便从python到c ++检索矩阵

非常感谢你。

2 个答案:

答案 0 :(得分:2)

您正在使用PyInt_AsLong(pValue)将Python对象pValue转换为C long标量。如果pValue是Numpy数组,这意味着您正在尝试将数组转换为数字,这仅适用于长度为1的数组:

  

只能将length-1数组转换为Python标量

不使用PyInt_AsLong,而是使用Numpy's C API提供的PyArray_*函数来访问数据;特别是,请参阅Array API部分。

答案 1 :(得分:0)

您想使用NumPy C API,可能是为了获取带

的数据指针
#include <numpy/arrayobject.h>
...
p = (uint8_t*)PyArray_DATA(pValue);

确定你确实得到了正确尺寸的数组。有关示例代码,请参阅我的hello.hpp