PyArray_SimpleNewFromData example

I know that this thing has been answered many times, and I also read the documentation, but still I cannot clearly understand how it works. Like in, I cannot understand how the values ​​are populated in my arguments. Examples do not explain this very clearly (or maybe I cannot). Can someone help me understand how the arguments of this function are populated? What should be their values? I need to pass a vector from C ++ to Python without reallocating memory. Any help is much appreciated. I have been stuck on this for many days.

My code that I am implementing is:

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;
}
+4
source share
1 answer

Function : :

 PyObject *
    PyArray_SimpleNewFromData(
        int nd, 
        npy_intp* dims, 
        int typenum, 
         void* data)
  • (data) . .

  • (dims) - , ; 1d- -1 ( , -1).

  • , (nd)

  • (typenum) .


, , 4 64- ints x:

,

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)
+4

Source: https://habr.com/ru/post/1589061/


All Articles