Click here to Skip to main content
15,847,583 members
Articles / Programming Languages / C#
Tip/Trick

Use "dynamic" to make PInvoke simple

Rate me:
Please Sign up or sign in to vote.
4.50/5 (2 votes)
24 Apr 2010CPOL 16.3K   3   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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
China China
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralGood! Pin
Shawn-USA2-May-13 20:14
Shawn-USA2-May-13 20:14 
Hi, Zhongzf,

The dynamic pinvoke uses DefinePInvokeMethod method to define pinvoke signature. Defining a Calli call is also one of the new ways to achieve PInvoke. You will be fine to call most of your native methods using either DefinePInvokeMethod or calli , but they did not work for all of the methods I tried.

Explict P/Invoke is still the best way to call native method.

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.