Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Use dynamic to make PInvoke simple

0.00/5 (No votes)
24 Apr 2010 1  
Introduction...
Introduction


Use the "dynamic" key word in C# 4.0 to make PInvoke simple.
The method is introduced by Miguel de Icaza in his web blog, in the article "C#'s Dynamic in Mono". and zhongzf has some changes, added support with "return value" and "ref, out parameter".
All the source code is check in on http://code.google.com/p/dynamicdllimport/


Using the code

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


with return value.

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


with ref, out parameter.

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;
   }
} 

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here