PyArray_SimpleNewFromData example

PyArray_SimpleNewFromData example

本文关键字:example SimpleNewFromData PyArray      更新时间:2023-10-16

我知道这件事已经回答了很多次,我也读了文档,但我仍然不能清楚地理解这是如何工作的。例如,我无法理解如何在其参数中填充值。这些例子并不能很清楚地解释它(或者可能是我不能)。有人能帮我理解这个函数的参数是如何填充的吗?他们的价值观应该是什么?我必须在不重新分配内存的情况下将一个向量从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("check0n");
// pDict is a borrowed reference 
pDict = PyModule_GetDict(pModule);
printf("check1n");
// pFunc is also a borrowed reference 
pFunc = PyDict_GetItemString(pDict, argv[2]);
printf("check2n");
//    if (PyCallable_Check(pFunc)) 
//    {
// Prepare the argument list for the call
//xarr1 = PyFloat_FromDouble(xarr[1]);
    printf("check3n");
c = PyArray_SimpleNewFromData(1,&m,NPY_FLOAT,(void *)fArray);
printf("check3n");
    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;
}

函数为:

 PyObject *
    PyArray_SimpleNewFromData(
        int nd, 
        npy_intp* dims, 
        int typenum, 
         void* data)
  • 最后一个参数(data)是数据的缓冲区。

  • 第二个参数(dims)是一个缓冲区,它的每个表项是一个维度;所以对于1d数组,它可以是长度为1的缓冲区(甚至是整数,因为每个整数都是长度为1的缓冲区)

  • 由于第二个参数是一个缓冲区,第一个参数(nd)告诉它的长度

  • 第三个参数(typenum)表示类型


例如,假设您在x:

有4个64位整数:

创建数组,使用

int dims[1];
dims[0] = 4;
PyArray_SimpleNewFromData(1, dims, NPY_INT64, x)

创建2X2矩阵,使用

int dims[2];
dims[0] = dims[1] = 2;
PyArray_SimpleNewFromData(2, dims, NPY_INT64, x)

确保您堵塞了上述方法所带来的内存泄漏。我猜在上面的x是一个类型为void *的指针。