Passing 2D c++ array to a python function and getting output back as 2D array

  c-api, c++, python

I have been stuck on this for a week now.I am intializing a 2D array of doubles and passing it to a simple
python function which multiplies it by 2 and returns it.

def in_arr_out_arr(arr_input):

    print(arr_input)
    arr_input2 = 2*arr_input

    return (arr_input2)

The print function prints garbage values to the console .

Here is the function Called

PyObject* call_python_function_array2d_input(PyObject * pFunc, double** args, int nRow, int nCol)
{
        // some issue check again
        
        import_array()
        PyArrayObject* np_arg;
        PyObject* pArgs, * pReturn , *_np_arg;
        const int SIZE{ nRow };
        npy_intp dims[2]{ nRow,nCol };
        const int ND =  2 ;
        
        np_arg = reinterpret_cast<PyArrayObject*>(PyArray_SimpleNewFromData(ND, dims, NPY_DOUBLE, reinterpret_cast<void*>(args)));
        
        pArgs = PyTuple_New(1);
        PyTuple_SetItem(pArgs, 0, reinterpret_cast<PyObject*>(np_arg));
        pReturn = PyObject_CallObject(pFunc, pArgs);
        
        cout << pReturn << "n";
        return pReturn;

}

This is the last version i tried by reading from some previous answer on this forum only.
It may have something to do with contigous block of memory allocation for np_arg but i dont have that
much expertise in pointers

Source: Windows Questions C++

LEAVE A COMMENT