zoukankan      html  css  js  c++  java
  • [原创]如何加载动态库、获取方法委托、卸载动态库

    C#在调用非托管动态库时,经常需要实时卸载动态库,本例演示如何加载、获取方法委托、卸载动态库:

    [DllImport("Kernel32.dll")]
    public static extern int LoadLibrary(string lpFileName);

    [DllImport("Kernel32.dll")]
    public static extern bool FreeLibrary(int hModule);

    [DllImport("Kernel32.dll")]
    public static extern IntPtr GetProcAddress(int hModule, string lpProcName);

    public delegate int readcard(int ai_czlx, [MarshalAs(UnmanagedType.LPArray)]byte[] errmsg);
    public delegate int writecard(int ai_czlx, byte[] ac_data, [MarshalAs(UnmanagedType.LPArray)]byte[] errmsg);

    public unsafe static string Read()
    {
    int hLib = LoadLibrary("lib\\rdcard.dll");
    IntPtr ptr = GetProcAddress(hLib, "readcard");
    readcard myfunc = (readcard)Marshal.GetDelegateForFunctionPointer(ptr, typeof(readcard));

    try
    {
    unsafe
    {
    int i = -1;
    byte[] bytes = new byte[200];
    try
    {
    i = myfunc(2, bytes);
    }
    catch (SEHException ex)
    {
    throw ex;
    }
    catch (Exception ex)
    {
    throw ex;
    }
    string res = Encoding.Default.GetString(bytes);
    return res;
    }
    }
    finally
    {
    FreeLibrary(hLib);
    }
    }

    public unsafe static int Write(string writeContent)
    {
    int hLib = LoadLibrary("lib\\rdcard.dll");
    IntPtr ptr = GetProcAddress(hLib, "writecard");
    writecard myfunc = (writecard)Marshal.GetDelegateForFunctionPointer(ptr, typeof(writecard));

    try
    {
    unsafe
    {
    byte[] bytes = new byte[200];
    string result = writeContent;
    byte[] results = Encoding.Default.GetBytes(result);
    int j = -1;
    try
    {
    j = myfunc(2, results, bytes);
    }
    catch
    {
    }

    return j;
    }
    }
    finally
    {
    FreeLibrary(hLib);
    }
    }

  • 相关阅读:
    关于ios7的适配问题
    iOS安全攻防(十八):数据保护API
    【Objective-C】OC中KVO的基本概念和使用方法
    pytest运行方式
    unittest中使用ddt做数据驱动
    unittest使用HtmlTestRunner显示报告
    unittest中的断言内容
    unittest指定跳过某些方法
    unittest运行时指定运行顺序
    xpath使用属性元素定位,包含 and 、or、not
  • 原文地址:https://www.cnblogs.com/hehexiaoxia/p/2882915.html
Copyright © 2011-2022 走看看