C#动态调用非托管DLL(一)

    技术2022-05-11  69

             尝试着在C#下调用以前Delphi写的一些DLL,基本实现动态调用,传入回调函数,及调用带结构数组指针作为参数的函数.

         虽然DllImport可以方便的静态调用DLL的函数,但在.net2.0中新增加了一个Marshal.GetDelegateForFunctionPointer 方法,可以将非托管函数指针转换为委托。 有了这个方法就可以用三个Windows API函数即:Loadlibrary,GetProcAddress和Freelibrary来实现动态调用DLL了.下面是实现DLL动态调用的静态类

    /****************************(如转载,请保留版权信息)************************ author:awin                                                               e-mail:mrzwin@21cn.com                                                    blog:  http://blog.csdn.net/awin                                       *****************************(如转载,请保留版权信息)************************/ using  System; using  System.Runtime.InteropServices; namespace  Awin.Common {    /// <summary>    /// DLL加载类    /// </summary>    internal class DllLoader    {        [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);        public 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   int  m_hDLL  =   0 // DLL句柄 private   delegate   int  ShowForm(IntPtr aHandle); private  ShowForm m_ShowForm; private   const   string  DLLNAEM  =   " XXX.dll " ;m_hDLL  =  DllLoader.LoadLibrary(DLLNAEM); if  (m_hDLL  ==   0 ) {    MessageBox.Show("加载失败!");    return;} m_ShowForm  =  (ShowForm) DllLoader.GetAddress(m_hPacsview,  " ShowForm " typeof  (ShowForm)); // 使用ShowForm   if  (m_ShowForm  !=   null )                m_ShowForm(iHandle); // 卸载DLL  DllLoader.FreeLibrary(m_hDLL); 

    下一篇再说说调用带结构数组指针作为参数的函数


    最新回复(0)