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

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

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

和我的c ++代码:

int main(int argc, char *argv[]) { int i; PyObject *pName, *pModule, *pDict, *pFunc, *pArgs, *pValue; 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 = UT*x print B return B 

我知道这个陈述有问题

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

非常感谢。

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

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

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

您想使用NumPy C API,可能是为了获取数据指针

 #include  ... p = (uint8_t*)PyArray_DATA(pValue); 

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