[Numpy-discussion] 32/64-bit machines, integer arrays and python ints

Travis Oliphant oliphant.travis at ieee.org
Thu Sep 28 13:03:56 CDT 2006


Bill Spotz wrote:
> I am wrapping code using swig and extending it to use numpy.
>
> One class method I wrap (let's call it myElements()) returns an array  
> of ints, and I convert it to a numpy array with
>
>      PyArray_SimpleNew(1,n,'i');
>   

You should probably use NPY_INT instead of 'i' for the type-code.  
> I obtain the data pointer, fill in the values and return it as the  
> method return argument.
>
> In python, it is common to want to loop over this array and treat its  
> elements as integers:
>
>      for row in map.myElements():
>          matrix.setElements(row, [row-1,row,row+1], [-1.0,2.0,-1.0])
>
> On a 32-bit machine, this has worked fine, but on a 64-bit machine, I  
> get a type error:
>
>      TypeError: in method 'setElements', argument 2 of type 'int'
>
> because row is a <type 'int32scalar'>.
>
> It would be nice if I could get the integer conversion to work  
> automatically under the covers, but I'm not exactly sure how to make  
> that work.
>   

Yeah, It can be confusing, at first.  You just have to make sure you are 
matching the right c-data-types. I'm not quite sure what the problem 
here is given your description, because I don't know what setElements 
expects.  

My best guess, is that it is related to the fact that a Python int uses 
the 'long' c-type.   Thus, you should very likely be using 
PyArray_SimpleNew(1, n, NPY_LONG) instead of int so that your integer 
array always matches what Python is using as integers.

The other option is to improve your converter in setElements so that it 
can understand any of the array scalar integers and not just the default 
Python integer.  

The reason this all worked on 32-bit systems is probably the array 
scalar corresponding to NPY_INT is a sub-class of the Python integer.  
It can't be on a 64-bit platform because of binary incompatibility of 
the layout.

Hope that helps.


-Travis





More information about the Numpy-discussion mailing list