Search code examples
python.netnumpyclr

How to use C# UInt16[,] in python


I am using clr to import c# dll in python

one of the functions return ushort[,] , which is considered as System.UInt16[,] in python

How can in convert System.UInt16[,] to numpy uint16 matrix?

I can do the conversion only by looping on the matrix, reading each element and assigning its value to the respective position in another numpy matrix, but this solution is very slow.

Is there a faster conversion method which can utilize numpy vectorization ?

Here's a sample for my loop

import clr
import os
import numpy as np

dll_name = os.path.join(os.path.abspath(os.path.dirname(__file__)), ("mydll") + ".dll")
clr.AddReference(dll_name)
from mynamespace import myclass
myobject = myclass()

numpy_matrix = np.empty([80,260],dtype = np.uint16)
SystemInt16_matrix = myobject.Getdata()
for i in range(20):
    for j in range(32):
        numpy_matrix[i,j]=SystemInt16_matrix[i,j]

Solution

  • I could find the solution, instead of the loop I should use np.fromiter & reshape

    import clr
    import os
    import numpy as np
    
    dll_name = os.path.join(os.path.abspath(os.path.dirname(__file__)), ("mydll") + ".dll")
    clr.AddReference(dll_name)
    from mynamespace import myclass
    myobject = myclass()
    
    SystemInt16_matrix = myobject.Getdata()
        numpy_matrix = np.fromiter(SystemInt16_matrix, np.int16).reshape((20, 32))