Altering/initializing NumPy array in C
Hello, I'm having issues with performing operations on an array in C and passing it back to Python. The array values seem to become unitialized upon being passed back to Python. My first attempt involved initializing the array in C as so: double a_fin[max_mth]; where max_mth is an int. I fill in the values of a_fin and then, before returning back to Python, I create a NumPy array in C and fill it in using a pointer to the a_fin array: npy_intp a_dims[2] = {max_mth, 1}; a_fin_array = (PyArrayObject *) PyArray_SimpleNewFromData(2, a_dims, NPY_DOUBLE, a_fin); I update the flags as so: PyArray_UpdateFlags(a_fin_array, NPY_OWNDATA); and return using: PyObject *Result = Py_BuildValue("OO", a_fin_array, b_fin_array); Py_DECREF(a_fin_array); (there is another array, b_bin_array that I create in this way and it suffers from the same issues). Immediately upon returning to Python, all of a_fin_array appears unitilized. This only happens in certain situations and sometime only part of the arrary will be unitilized. I check the values of a_dim and a_fin_array in C using gdb and they appear as expected, but are over-written with unitialized values upon returning to Python. I've tried initializing in Python and then passing the NumPy array in instead of initializing in C, but the effects of the calculations in C are still not kept. My feeling is that, with the Numpy C-API, this should be a simple process, but I'm having a lot of trouble with it. Any help would be much appreciated. I didn't want to give too much information in the post, but please let me know what other information would be useful. -Bart
On 1 Jan 2014 13:57, "Bart Baker" <bartbkr@gmail.com> wrote:
Hello,
I'm having issues with performing operations on an array in C and passing it back to Python. The array values seem to become unitialized upon being passed back to Python. My first attempt involved initializing the array in C as so:
double a_fin[max_mth];
where max_mth is an int.
You're stack-allocating your array, so the memory is getting recycled for other uses as soon as your C function returns. You should malloc it instead (but you don't have to worry about free'ing it, numpy will do that when the array object is deconstructed). Any C reference will fill you in on the details of stack versus malloc allocation. -n
You're stack-allocating your array, so the memory is getting recycled for other uses as soon as your C function returns. You should malloc it instead (but you don't have to worry about free'ing it, numpy will do that when the array object is deconstructed). Any C reference will fill you in on the details of stack versus malloc allocation.
OK, that makes a lot of sense. I changed them to malloc's of the appropriate size and now things seems to be working well. It also led to a good read on stack vs heap. Thanks a lot, Bart
participants (2)
-
Bart Baker -
Nathaniel Smith