Question

I wrote a python extension in C++ to work with numpy arrays. I have a memory issue.

I have a 3D numpy array with values > 0 before I call the extension. Once I am in the extension I get the numpy array using this function:

PyArrayObject * myArray = NULL;

if (!PyArg_ParseTuple(args, "O!", 
    &PyArray_Type,&myArray))  return NULL;

Using " !O " should borrow the reference to python so that I have directly access to my numpy array.

Then I access the data:

float * myData = (float *) myArray->data;

int nbFrames =  array -> dimensions[0];
int nbRows =  array -> dimensions[1];
int nbCols =  array -> dimensions[2];

Later I check that values present in myArray are still positive:

for(int i = 0 ; i < nbFrames; i ++){
    for( int j = 0 ; j < nbRows; j ++){
        for(int k = 0 ; k < nbCols; k++){
            if( myData[ i * nbCols * nbRows + j * nbCols + k ] < 0){
                perror("Value < 0\n");
                exit(1);
            }  
         }
    }
}

And every time I run into the case where the value is < 0. And it is not just "-0.0000", it is rather "-19.73".

So does anyone already encountered this kind of problem or does anyone know where it comes from and how to solve it?

Was it helpful?

Solution

For those who will read this question, the answer was provided by sega_sai , in the comments of my question. The trick was to make sure that the array is C contiguous. To do so, you can either use the option "order = 'C' " when creating the array, for 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 it as a c contiguous array by doing:

np.ascontiguousarray(a)

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top