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

原文地址:https://www.cnblogs.com/zeroone/p/5449493.html