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);
    }
    }

  • 相关阅读:
    Linq分组后,再对分组后的每组数据进行排序,获取每组的第一条记录
    C/C++ 常量存储: 总结
    张庆科(山师大硕导简介) [转载]
    composer [packagist]包制作(入门篇)
    MMGCN: Multi-modal Graph Convolution Network for Personalized Recommendation of Micro-video
    opencv.js编译
    推荐
    推荐
    推荐
    Azure Automation (10) 在Automation中动态修改Azure Analysis Firewall防火墙规则
  • 原文地址:https://www.cnblogs.com/hehexiaoxia/p/2882915.html
Copyright © 2011-2022 走看看