使用dynamic让PInvoke更简单

本文介绍了如何使用C#4.0的动态特性来简化DLL导入的过程,并提供了动态加载DLL及调用方法的具体示例,包括返回值和ref(out)参数的支持。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值