1

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?

2
  • Did you make sure the numpy array is continuous ? print arr.flags['C_CONTIGUOUS'] Also, are you sure that the your numpy array has the same number of bits per value as your float ? Commented May 6, 2013 at 11:01
  • Perfect! Thank you very much!! That was actually the problem. My array wasn't C contiguous. It was 'aligned'. Commented May 6, 2013 at 12:04

1 Answer 1

2

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)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.