IronPython調用C# DLL函數方法


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. 最后運行結果如下

IronPython


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM