Python/Numpy C++ extension: memory issue -


i wrote python extension in c++ work numpy arrays. have memory issue.

i have 3d numpy array values > 0 before call extension. once in extension numpy array using function:

pyarrayobject * myarray = null;  if (!pyarg_parsetuple(args, "o!",      &pyarray_type,&myarray))  return null; 

using " !o " should borrow reference python have directly access numpy array.

then access data:

float * mydata = (float *) myarray->data;  int nbframes =  array -> dimensions[0]; int nbrows =  array -> dimensions[1]; int nbcols =  array -> dimensions[2]; 

later check values present in myarray still positive:

for(int = 0 ; < nbframes; ++){     for( int j = 0 ; j < nbrows; j ++){         for(int k = 0 ; k < nbcols; k++){             if( mydata[ * nbcols * nbrows + j * nbcols + k ] < 0){                 perror("value < 0\n");                 exit(1);             }            }     } } 

and every time run case value < 0. , not "-0.0000", rather "-19.73".

so encountered kind of problem or know comes , how solve it?

for read question, answer provided sega_sai , in comments of question. trick make sure array c contiguous. so, can either use option "order = 'c' " when creating array, instance:

a = np.array([1,2,3,4],order='c') 

(for more information see numpy reference: http://docs.scipy.org/doc/numpy/reference/generated/numpy.array.html) or transform c contiguous array doing:

np.ascontiguousarray(a) 

(for mor information see numpy reference http://docs.scipy.org/doc/numpy/reference/generated/numpy.ascontiguousarray.html)


Comments