使用dynamic让PInvoke更简单

dynamic user32 = new DynamicDllImport("user32.dll", callingConvention : CallingConvention.Winapi);
user32.MessageBox(0, "Hello World", "Platform Invoke Sample", 0);

能够这样调用动态连接库中的方法,是不是很方便?!这就是Miguel de Icaza在他的blog中介绍mono中dynamic提到的方法。

C# 4's Dynamic in Mono  (http://tirania.org/blog/archive/2009/Aug-11.html)

瑞雪年又把它丰富了一下,加入了返回值和ref (out)参数支持,示例:

dynamic asmproject = new DynamicDllImport("asmproject.dll");
int value = asmproject.add<int>(3, 4);
Console.WriteLine(value);      



dynamic sdl = new DynamicDllImport("SDL.dll", CharSet.Ansi);
Sdl.SDL_Rect rect = new Sdl.SDL_Rect(
                    0,
                    0,
                    (short)width,
                    (short)height);
int result = sdl.SDL_FillRect<int>(rgbSurfacePtr, ref rect, 0);


Sdl.SDL_Event evt;
while (sdl.SDL_WaitEvent(out evt) != 0)
{
   if (evt.type == Sdl.SDL_QUIT)
   {
       break;
    }
}

具体实现代码在这里就不粘了,和引用的《C# 4's Dynamic in Mono》基本相同,只是作了部分添加和修改,大家可以到 http://code.google.com/p/dynamicdllimport/

查看或下载,如果有人在使用过程中发现bug或有更好的方法,本人真心希望能告之,有更新代码可以上传至上面的google code网站,希望更多的人能用上最新的代码,先在这里谢谢了!

类库下载:http://dynamicdllimport.googlecode.com/files/DynamicDllImport_lib.zip

示例下载:http://dynamicdllimport.googlecode.com/files/DynamicDllImport_Sample.zip

原码下载:http://dynamicdllimport.googlecode.com/files/DynamicDllImport_source_code.zip

原文地址:https://www.cnblogs.com/zhongzf/p/1718151.html