How can I pass&return ndarray between python and c++? - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: How can I pass&return ndarray between python and c++? (/thread-32830.html) |
How can I pass&return ndarray between python and c++? - JESuh - Mar-09-2021 Hello, I have some questions about python c extension. I want to pass ndarray from python to c++, do some job to change the values in this ndarray, and then return to python code(and then I'll do some more job in python code using 'a'). I use windows 10 64bit, python 3.7.6 32bit, visual studio 2019. Here I attached some part of my code, but it works only once, even if there is a for loop to run cfunc n times. Also returned value have some problem (I don't know exactly, I cannot see nor plot the returned array.) * python code import cModule for i in range(0,n): print(a[i]) # it works only once and doesn't do anything in the second loop. It just become silent and finished the code without any error nor warning message. some_value, a = cModule.cfunc(a, ...)* c++ code #include <Python.h> #include <numpy\ndarraytypes.h> #include <numpy\ndarrayobject.h> #include <numpy\arrayobject.h> int cfunc(double* a, ...) { ... // Do some job to change a } static PyObject* cfunc_translate(PyObject* self, PyObject* args) { PyArrayObject* a_py; double* a; if (!PyArg_ParseTuple(args, "O", &a)) return NULL; } a = (double*)a_py->data; int length_a = 512*512; int some_value = cfunc(a); npy_intp dims[1]; dims[0] = 1; PyObject* a_return = PyArray_SimpleNewFromData(length_a, dims, NPY_DOUBLE, a); // This part doesn't work from the 2nd loop in the python code. Or if I try to see the elements in 'a', it just become silent and finished the code without any error nor warning message. free(a); Py_XDECREF(a_py); return Py_BuildValue("iO", some_value, a_return);Probably 'a' is distorted in some way when I return the value. But I don't know how can I solve this problem. (Returned a is also ndarray.) Please let me know if you have any idea or need further information. Thank you so much! Best wishes, JESuh |