Calling .NET objects from Python

General topics that don't fit into other forum categories

Calling .NET objects from Python

Postby tunc » 05 Jun 2015, 19:15

I have recently developed an interest in the programming language Python that I use like an open-source Matlab with its modules like NumPy, Pandas and MatPlotLib.

I am currently working on a simple integration module in python, which will enable python users to call table-valued functions of the .net library finaquant protos.

Calling .NET objects from Python is quite easy if you install a Python module named pythonnet using the PIP package manager, that automatically downloads and installs Python modules.

After installing PIP on your computer, run following command in your terminal (command line window) in order to install Python for NET:
Code: [Select all] [Expand/Collapse] [Download] (Untitled.txt)
  1. pip install pythonnet
GeSHi ©


You can now access .NET classes using the Python module named CLR:
Code: [Select all] [Expand/Collapse] [Download] (Untitled.txt)
  1. import clr
  2. import time
  3. from System.Windows.Forms import Form  # import a .NET class
  4.  
  5. clr.AddReference("System.Windows.Forms")  # add an assemby reference
  6. f = Form()  # create a Form object in Python
  7. f.Show()
  8. time.sleep(3)  # wait 3 seconds before closing the form
  9. f.Close()
GeSHi ©


You can also import classes from your custom .NET assembly (dll file) in Python provided that your assemby resides in the same directory with the calling Python script:
Code: [Select all] [Expand/Collapse] [Download] (Untitled.txt)
  1. import clr
  2. from MySimpleMath import SimpleMath as sm # import static class named SimpleMath
  3. print sm.AddNumbers(7, 9)
GeSHi ©


Following Python code example shows how a NumPy array can be converted to a .NET array:
Code: [Select all] [Expand/Collapse] [Download] (Untitled.txt)
  1. import clr
  2. import sys
  3. import numpy as np
  4. import System
  5.  
  6. def ConvertNumPyToNETarray(nparr):
  7.     a = np.array([1])
  8.     # check if nparr is a NumPy array
  9.     if type(nparr) != type(a):
  10.         print "Wrong input type: Input argument must be a NumPy array!"
  11.         raise Exception('Wrong Input Type: Input argument must be a NumPy array!')
  12.    
  13.     # check dimension of nparr
  14.     dims = len(nparr.shape)
  15.     if dims > 2:
  16.         raise Exception('Too Many Dimensions: The array to be converted cannot have more than 2 dimensions!')
  17.    
  18.     if dims == 1:
  19.         arrtype = type(nparr[0]).__name__
  20.         (x1,) = nparr.shape
  21.     else:
  22.         arrtype = type(nparr[0,0]).__name__
  23.         (x1,x2) = nparr.shape
  24.    
  25.     # check type of nparr
  26.    
  27.     if arrtype.find('float') > -1:
  28.         if dims == 1:
  29.             arr = Array.CreateInstance(System.Double, x1)
  30.             for ind in range(x1):
  31.                 arr[ind] = nparr[ind]
  32.         else:   # dims == 2
  33.             arr = Array.CreateInstance(System.Double, x1, x2)
  34.             for ind1 in range(x1):
  35.                 for ind2 in range(x2):
  36.                     arr[ind1, ind2] = nparr[ind1, ind2]
  37.     elif arrtype.find('int') > -1:
  38.         if dims == 1:
  39.             arr = Array.CreateInstance(System.Int64, x1)
  40.             for ind in range(x1):
  41.                 arr[ind] = nparr[ind]
  42.         else:   # dims == 2
  43.             arr = Array.CreateInstance(System.Int64, x1, x2)
  44.             for ind1 in range(x1):
  45.                 for ind2 in range(x2):
  46.                     arr[ind1, ind2] = nparr[ind1, ind2]
  47.     elif arrtype.find('string') > -1:
  48.         if dims == 1:
  49.             arr = Array.CreateInstance(System.String, x1)
  50.             for ind in range(x1):
  51.                 arr[ind] = nparr[ind].tostring()
  52.         else:   # dims == 2
  53.             arr = Array.CreateInstance(System.String, x1, x2)
  54.             for ind1 in range(x1):
  55.                 for ind2 in range(x2):
  56.                     arr[ind1, ind2] = nparr[ind1, ind2].tostring() 
  57.     else:
  58.         raise Exception('Invalid Data Type: Data type of the input array must be float, int or string.')
  59.    
  60.     return arr
  61.        
  62. #x = 5
  63.  
  64. # float
  65. x = np.array([1.5, 2, 3, 4.3, 5.2], float)
  66. xnet = ConvertNumPyToNETarray(x)
  67. print "xnet[1] = " , xnet[1]
  68. print "xnet[4] = " , xnet[4]
  69.  
  70. x = np.array([[1.5, 2, 4],[3,5,7]], float)
  71. xnet = ConvertNumPyToNETarray(x)
  72. print "xnet[1,0] = " , xnet[1,0]
  73. print "xnet[1,2] = " , xnet[1,2]
  74.  
  75. # int
  76. x = np.array([1, 2, 3, 4, 5], int)
  77. xnet = ConvertNumPyToNETarray(x)
  78. print "xnet[1] = " , xnet[1]
  79. print "xnet[4] = " , xnet[4]
  80.  
  81. x = np.array([[1, 3, 5],[9,11,15]], int)
  82. xnet = ConvertNumPyToNETarray(x)
  83. print "xnet[1,0] = " , xnet[1,0]
  84. print "xnet[1,2] = " , xnet[1,2]
  85.  
  86. # string
  87. x = np.array(['ali', 'veli', 'hasan', 'kamil'], str)
  88. xnet = ConvertNumPyToNETarray(x)
  89. print "xnet[1] = " , xnet[1]
  90. print "xnet[3] = " , xnet[3]
  91.  
  92. x = np.array([['ali', 'veli', 'hasan'],['semih','dursun', 'kamil']], str)
  93. xnet = ConvertNumPyToNETarray(x)
  94. print "xnet[1,0] = " , xnet[1,0]
  95. print "xnet[1,1] = " , xnet[1,1]
  96.  
  97. # to prevent CMD from closing quickly
  98. raw_input()
  99.  
GeSHi ©

Tunc
tunc
 
Posts: 25
Joined: 22 Jul 2014, 19:29
Location: Switzerland

Return to General

Who is online

Users browsing this forum: No registered users and 0 guests

cron