Sometimes it is necessary to use an assembly that was not created in .Net. This usually involves doing some low level things that are not native to C# or .Net and require you to import an existing assembly, perhaps a Win32 assembly, or to write your code in C++ and then import that into C#.
Let’s say for example you wanted to call the Win32 MessageBeep method to output an audible prompt to your user when they type something incorrectly. Yes, I know that would be annoying but this is just an example.
First we need to call the Win32 assembly with P/Invoke like this.
[DllImport("User32.dll")]
static extern Boolean MessageBeep(UInt32 beepType);
Now this imports the MessageBeep functionality so we can use it in C#. Now all you do is call it like a normal Method passing the beep type as a parameter.
MessageBeep(0);
It is that simple. P/Invoke gives use some nice flexibility to leverage existing Win32 API functions that may be missing from C# or reuse unmanaged code we have written for other projects.
Did You Enjoy This Post?
Be sure to grab my RSS feed so you don't miss out on more great articles.
This Post Was Brought To You By
How do I save time? I use FreshBooks for invoicing.
Get Information Technology magazine subscriptions and white papers for FREE!

Did you like this post? Be sure to

Recent Comments