zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    POJ 1330 Nearest Common Ancestors(LCA Tarjan算法)
    LCA 最近公共祖先 (模板)
    线段树,最大值查询位置
    带权并查集
    转负二进制
    UVA 11437 Triangle Fun
    UVA 11488 Hyper Prefix Sets (字典树)
    UVALive 3295 Counting Triangles
    POJ 2752 Seek the Name, Seek the Fame (KMP)
    UVA 11584 Partitioning by Palindromes (字符串区间dp)
  • 原文地址:https://www.cnblogs.com/zeroone/p/5449493.html
Copyright © 2011-2022 走看看