P/Invoke : Calling C++ from C#

P/Invoke is used as a noun when referring to the COM Interop functionality of the CLR and is used as a verb when referring to the use of this feature. Using the P/Invoke service in the .NET Compact Framework includes three primary steps: declaration, invocation, and error handling.

Sample Code:
Let's see how to call the Win32 MessageBeep function whose unmanaged declaration is shown in the following code:
BOOL MessageBeep(
UINT uType // beep type

You'll need the following code to add to a class or struct definition in C# in order to call MessageBeep:
static extern Boolean MessageBeep(UInt32 beepType);

Surprisingly, this code is all that's required before your managed code can suddenly call the unmanaged MessageBeep API. It's not a method call, but an
extern method definition. (Also, it's as close to a straight port from C that C# will allow, so it is a helpful starting point for introducing some concepts.) A possible call from managed code might look like this:

Now, notice that the MessageBeep method was declared as
static. This is a requirement for P/Invoke methods because there is no consistent notion of an instance in the Windows API. Next, notice that the method is marked as extern. This is your hint to the compiler that you mean for the method to be implemented by a function exported from a DLL, and therefore there is no need for you to supply a method body.


1. PInvoke Interop Assistant -
Brief: In marshalling, there are a bunch of attributes and rules. Understanding all those attributes and rules seem a bit daunting. In order to make developing work more efficient and easier on those attributes and the rules, P/Invoke Interop Assistant comes out. It is a toolkit that helps developers to efficiently convert from C to managed P/Invoke signatures or verse visa. This is conceptually similar to TlbImp for COM Interop which generates managed proxy entry points based on some formal description of the unmanaged side but it works for P/Invoke. The toolkit was first released on MSDN Magazine website in Jan, 2008.


2. P/Invoke sample code msi - http://msdn.microsoft.com/en-us/library/aa719104.aspx

3. Calling Win32 DLLs in C# with P/Invoke -


4. P/Invoke Documentation (msdn) - http://msdn.microsoft.com/en-us/library/26thfadc.aspx

5. Interoperating with Unmanaged Code -

6. Using P/Invoke to Call Unmanaged APIs from Your Managed Classes -

7. Managed, Native, and COM Interop Team - http://www.codeplex.com/clrinterop

8. CLR INSIDE OUT - http://msdn.microsoft.com/en-us/magazine/cc164193.aspx

9. Calling Managed .NET Function from Unmanaged Windows Custom DLL -

10. TLBIMP -
TLBIMP is a .NET SDK tool that creates an Interop assembly from a COM type library. This project is a managed code implementation of TLBIMP.

11. Best Practices for Managed And Native Code Interoperability by Jesse Kalpan - http://msdn.microsoft.com/en-us/magazine/2009.01.clrinsideout.aspx

12. A wiki for .NET developers - http://pinvoke.net/