C# DLL源碼
using System; using System.Collections.Generic; using System.Text; using System.Security.Cryptography; namespace Common { public class SimpleHash { public string HashCalc(byte[] audioBuffer, byte[] key) { ...... return result; } } }
需要在IronPython腳本中調用HashCalc函數,Python腳本如下:
import clr import System clr.AddReferenceToFile("SimpleHash.dll") from Common import * class HashPy(SimpleHash): def __init__(self): pass def HashCalc(self,arg1,arg2): #str to byte[] arg1=System.Text.Encoding.Default.GetBytes(arg1) arg2=System.Text.Encoding.Default.GetBytes(arg2) return SimpleHash.HashCalc(self,arg1,arg2) audiobuff='1234567812345678123456781234567812345678123456781234567812345678\ 123456781234567812345678123456781234567812345678123456781234567812345678\ 123456781234567812345678123456781234567812345678123456781234567812345678\ 1234567812345678123456781234567812345678123456781234567812345678' key='12345678' print HashPy().HashCalc(audiobuff,key)
詳細說明:
1. clr.AddReferenceToFile("SimpleHash.dll") 加載DLL文件
2. from Common import * 導入命名空間
3. 由於C#方法HashCalc不是靜態方法,需要先定義類,再進行訪問。若HashCalc為靜態方法,則IronPython腳本可直接調用:
namespace Common { public class SimpleHash { public static string HashCalc(byte[] audioBuffer, byte[] key) { ... return ToHex(result, 32); } } }
clr.AddReferenceToFile("SimpleHash.dll") from Common import * … SimpleHash. HashCalc(audiobuff,key)
4. C#方法參數為byte[]格式,需要將str轉換為byte[]格式,否則會報錯“TypeError: expected Array[Byte], got str”,相互轉換代碼如下:
import System #String To Byte[]: byte[] byteArray = System.Text.Encoding.Default.GetBytes(str); #Byte[] To String: string str = System.Text.Encoding.Default.GetString(byteArray);
5. 最后運行結果如下

