Search code examples
python-3.xpython-2.7numpypython.netintptr

python.NET upgrade to python 3.7: IntPtr to numpy array constructor not matching given arguments anymore


The following code to copy a .NET array to a numpy array works in python 2.7.17 but not anymore in python 3.7.7:

import clr, numpy
from System import Array, Int32, IntPtr
from System.Runtime.InteropServices import Marshal

n = 10
net_arr = Array.CreateInstance(Int32, n)
for i in range(0, n): net_arr[i] = i

np_arr = numpy.zeros([n], int)
np_ptr = IntPtr.__overloads__[int](np_arr.__array_interface__['data'][0])
Marshal.Copy(net_arr, 0, np_ptr, net_arr.Length)
print(np_arr)

# python2 output:
[ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9]

# python3 output:
Traceback (most recent call last):
  File "test.py", line 10, in <module>
    np_ptr = IntPtr.__overloads__[int](np_arr.__array_interface__['data'][0])
TypeError: no constructor matches given arguments

I'm aware that there were some changes to python types from 2 to 3 but searching and playing around with the constructor didn't help me find a solution. Thanks for any help!


Solution

  • Use Int64:

    from System import Array, Int32, Int64, IntPtr
    ...
    IntPtr.__overloads__[Int64](np_arr.__array_interface__['data'][0])