我知道这个问题已经被回答了很多次,我也阅读了文档,但我仍然无法清楚地理解这是如何工作的.在中,我无法理解如何在其参数中填充值.这些例子不是很清楚地解释它(或者可能是我不能).谁能帮助我了解这个函数的参数是如何填充的?他们的价值观应该是什么?我必须将一个从C++传递到Python的向量而不重新分配内存.任何帮助深表感谢.很多天我都坚持这个.
我正在实现的代码:
int main(int argc, char *argv[])
{
PyObject *pName, *pModule, *pDict, *pFunc, *pValue, *pArgs,*pXVec,*c, *xarr1;
int i;
float fArray[5] = {0,1,2,3,4};
//float *p = &fArray[0] ;
npy_intp m = 5;
//void* PyArray_GetPtr(PyArrayObject* aobj, npy_intp* ind)¶
// Initialize the Python Interpreter
Py_Initialize();
PySys_SetArgv(argc, argv);
// Build the name object
pName = PyString_FromString(argv[1]);
// Load the module object
pModule = PyImport_Import(pName);
printf("check0\n");
// pDict is a borrowed reference
pDict = PyModule_GetDict(pModule);
printf("check1\n");
// pFunc is also a borrowed reference
pFunc = PyDict_GetItemString(pDict, argv[2]);
printf("check2\n");
// if (PyCallable_Check(pFunc))
// {
// Prepare the argument list for the call
//xarr1 = PyFloat_FromDouble(xarr[1]);
printf("check3\n");
c = PyArray_SimpleNewFromData(1,&m,NPY_FLOAT,(void *)fArray);
printf("check3\n");
pArgs = PyTuple_New(1);
PyTuple_SetItem(pArgs,0, c);
pValue = PyObject_CallObject(pFunc, pArgs);
if (pArgs != NULL)
{
Py_DECREF(pArgs);
}
//}
// else
// {
// PyErr_Print();
// }
// Clean up
Py_DECREF(pModule);
Py_DECREF(pName);
// Finish the Python Interpreter
Py_Finalize();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
功能是:
PyObject *
PyArray_SimpleNewFromData(
int nd,
npy_intp* dims,
int typenum,
void* data)
Run Code Online (Sandbox Code Playgroud)
最后一个参数(data)是数据的缓冲区.让我们放弃它.
第二个参数(dims)是一个缓冲区,每个条目都是一个维度; 所以对于1d数组,它可以是长度为1的缓冲区(甚至是整数,因为每个整数是长度为1的缓冲区)
由于第二个参数是缓冲区,因此第一个参数(nd)告诉它的长度
第三个参数(typenum)表示类型.
例如,假设您有4个64位整数x:
要创建数组,请使用
int dims[1];
dims[0] = 4;
PyArray_SimpleNewFromData(1, dims, NPY_INT64, x)
Run Code Online (Sandbox Code Playgroud)
要创建2X2矩阵,请使用
int dims[2];
dims[0] = dims[1] = 2;
PyArray_SimpleNewFromData(2, dims, NPY_INT64, x)
Run Code Online (Sandbox Code Playgroud)