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

标签 c++ python c numpy

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

only length-1 arrays can be converted to Python scalars

和我的 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(pValue) Can anyone tell me how to fix that in order to retrieve the matrix from python to c++

非常感谢。

最佳答案

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

only length-1 arrays can be converted to Python scalars

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

关于c++ - 如何将数组从c++传递到python函数并将python返回的数组检索到c++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9922801/

相关文章:

c - C 中指向结构与 malloc 的指针?

c++ - 结构名称不隐藏变量名称

c++ - 根据解析的字符串创建对象

c - 从 listen 和 fork 到 xinetd

python - 使用Python继承解决循环依赖

python - 迁移时 Django 错误(int() 和 datetime.datetime)

c - 由于内存指针的 free() 语句,非零退出状态 139

c++ - 依赖遍历器中缺少 Dll

c++ - 客户端/服务器设置仅在同一台计算机上有效

python - 将 str.contains 映射到 pandas DataFrame