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

  • 相关阅读:
    <<构建之法>>--第二次作业
    锁的内存语义
    MySQL触发器
    每天一个小示例 opencv(1)颜色直方图的统计 calcHist_Demo.cpp
    通过支持向量排名法来做行人鉴定
    数字信号处理101——DSP系统设计入门课程(1)
    matlab 与c++的混编
    FPGA图像处理之行缓存(linebuffer)的设计一
    基于FPGA的数字识别的实现
    使用matlab生成sine波mif文件
  • 原文地址:https://www.cnblogs.com/hehexiaoxia/p/2882915.html
Copyright © 2011-2022 走看看