架构深渊

慢慢走进程序的深渊……关注领域驱动设计、测试驱动开发、设计模式、企业应用架构模式……积累技术细节,以设计架构为宗。
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

提供 .Net 下调用非托管Dll内部函数的快捷方法

Posted on 2009-01-06 22:42  chen eric  阅读(362)  评论(0编辑  收藏  举报
提供 .Net 下调用非托管Dll内部函数 的快捷方法2008年12月12日 星期五 下午 10:241,用C#实现一个DllImported 类,内部利用DllImport 访问kernel32.dll的LoadLibrary和GetProcAddress

       [DllImport(
"kernel32.dll", EntryPoint = "LoadLibrary")]
        
public static extern int LoadLibrary( string lpLibFileName );
        [DllImport(
"kernel32.dll", EntryPoint = "GetProcAddress")]
        
public static extern IntPtr GetProcAddress(int hModule, string lpProcName);

2,利用Marshal.GetDelegateForFunctionPointer 将非托管指针转化为委托

类代码如下:

using System;
using System.Collections.Generic;
using System.Text;

///////////////添加命名空间/////////////////////////
using System.Runtime.InteropServices;


namespace DllImported
{
    
public class CDllImported
    {

        [DllImport(
"kernel32.dll", EntryPoint = "LoadLibrary")]
        
public static extern int LoadLibrary( string lpLibFileName );
        [DllImport(
"kernel32.dll", EntryPoint = "GetProcAddress")]
        
public static extern IntPtr GetProcAddress(int hModule, string lpProcName);
        
public CDllImported()
        {           
        }
        
/// <summary>
        
/// 获取非托管DLL内部函数
        
/// </summary>
        
/// <param name="delegateName">托管函数定义类型,用typeof(your delegate typeof)传入 </param>
        
/// <param name="dllName">Dll路径 </param>
        
/// <param name="procName">要获取的函数名称</param>
        
/// <returns></returns>
        public object   GetApi (Type delegateName, string dllName,string procName)
        {
            IntPtr api 
= GetProcAddress(LoadLibrary(dllName), procName);
            
return (object)Marshal.GetDelegateForFunctionPointer(api, delegateName);
        }
         
    }
}


编译产生一个DllImported的 dll组件。

在Vb里调用Api

1 先添加上面的组件

2    定义委托 Delegate Function msgDelegate(ByVal hwnd As IntPtr, ByVal strText As String, ByVal strCaption As String, ByVal type As Int32) As Int


3 实现调用

   Dim api As New DllImported.CDllImported

    Dim msg As msgDelegate
= api.GetApi(Gettype(msgDelegate) , "user32.dll""MessageBoxW")
     msg(IntPtr.Zero, 
"Done""Change"0)

类似的可以在C#内调用,由于类代码是C#写的,调用起来很容易,此略去。