1

I am trying to get some data from an module which is a shared object wrapped with ctypes. The data is a numeric array so I used numpy array to store the data. But I learned that I don't understand how numpy organize the array in memory.

If I had a C function that would fill a array like below:

int filler(int* a,int length){
        int i=0;
        for(i=0;i<length;i++){
                a[i]=i;
        }
        return 0;
}

Then I would call this function in python using ctypes

import ctypes
import numpy
lib = ctypes.cdll.LoadLibrary("libname")    
data = numpy.zeros((1,10),dtype=numpy.int16)
lib.filler(data.ctypes.data,ctypes.c_int(10))
print data

But my output comes out this way.

dtype=numpy.int16
[[0 0 1 0 2 0 3 0 4 0]]

This would make sense if int was 32 bit, but I suppose C int are 16 bits (GCC in openSUSE in a x86 intel machine). I tried running with dtypes being 32 bits and strangely I get the result I want:

dtype=numpy.int32
[[0 1 2 3 4 5 6 7 8 9]]

Trying to make sense of what is happening I ran with int8 and I got the following:

dtype=numpy.int8
[[0 0 0 0 1 0 0 0 2 0]]

I did give a look give a look at numpy docs, but so far I have not found what the answer.

1 Answer 1

2

This would make sense if int was 32 bit, but I suppose C int are 16 bits (GCC in openSUSE in a x86 intel machine). I tried running with dtypes being 32 bits and strangely I get the result I want:

Not strange at all: your supposition is wrong, and your machine is 32 bit with a 32 bit int and a 16 bit short int.. unless you're doing some (rather admirable) retrocomputing!

Check sizeof(int) and multiply by 8, or simply store numbers in an int and print them out, to convince yourself.

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.