Python Forum
How can I pass&return ndarray between python and c++?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How can I pass&return ndarray between python and c++?
#1
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
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How do I pass a dictionary for the in3_registry value for the Incubed Python API? nilesh 0 616 Jan-11-2021, 11:19 AM
Last Post: nilesh
  Pass by object reference when does it behave like pass by value or reference? mczarnek 2 1,240 Sep-07-2020, 08:02 AM
Last Post: perfringo
  Function to return list of all the INDEX values of a defined ndarray? pjfarley3 2 970 Jul-10-2020, 04:51 AM
Last Post: pjfarley3
  Syntax to print ndarray member of class containing ndarray pjfarley3 6 1,622 Jul-09-2020, 06:29 AM
Last Post: pjfarley3
  Pass by reference vs Pass by value leodavinci1990 1 1,142 Nov-20-2019, 02:05 AM
Last Post: jefsummers
  Pass variable script return twice output problem Faruk 8 2,245 Dec-26-2018, 11:57 AM
Last Post: Faruk

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020