zoukankan      html  css  js  c++  java
  • 在 C# 中动态调用 native dll 的导出函数

    在 C++ 中我们能够通过 LoadLibrary,  GetProcAddress 来动态调用 dll 的导出函数.
    在 C# 中也能够用这样的方式吗?
    在 DotNet 2.0 里面这样是可以的, 这完全得益于 2.0新增的一个函数
    Marshal.GetDelegateForFunctionPointer 方法
    此方法在 .NET Framework 2.0 版中是新增的。

    将非托管函数指针转换为委托。
    实例代码如下:

    public delegate int MsgBox(int hwnd,string msg,string cpp,int ok);

            [DllImport(
    "Kernel32")]
            
    public static extern int GetProcAddress(int handle, String funcname);
            [DllImport(
    "Kernel32")]
            
    public static extern int LoadLibrary(String funcname);
            [DllImport(
    "Kernel32")]
            
    public static extern int FreeLibrary(int handle);

            
    private static Delegate GetAddress(int dllModule, string functionname, Type t)
            
    {
                
    int addr = GetProcAddress(dllModule, functionname);
                
    if (addr == 0
                    
    return null
                
    else 
                    
    return Marshal.GetDelegateForFunctionPointer(new IntPtr(addr), t);
            }


            
    private void button1_Click(object sender, EventArgs e)
            
    {
                
    int huser32 = 0;
                huser32 
    = LoadLibrary("user32.dll");         
                MsgBox mymsg 
    = (MsgBox)GetAddress(huser32, "MessageBoxA"typeof(MsgBox));
                mymsg(
    this.Handle.ToInt32(), txtmsg.Text, txttitle.Text , 64);
                FreeLibrary(huser32);
            }


  • 相关阅读:
    MYbatis调试日记(三)
    Mybatis错误调试(二)
    【转载】MyBatis之传入参数
    Mybatis代码调试问题总结(一)
    【转载】Mybatis多参数查询映射
    未整理的资源
    Strace--系统调用分析问题集锦
    java初始化过程中成员变量
    java三元表达式编程规范问题
    转:Java的一道面试题----静态变量初始化过程
  • 原文地址:https://www.cnblogs.com/rick/p/apicall.html
Copyright © 2011-2022 走看看