The article aims to shed some light on an irksome topic, in managed code, named P/Invoke. The article contains a useful table of how to translate managed to unmanaged types, short code examples (in C#), tips and a list of resources.
You will not find here confound theoretical information about what P/Invoke is, but an essential knowledge. The article is by no means a complete guide and I am not pretending to be an expert in this filed, only one with some experience.
Working in a managed environment like the .NET Framework is fun. With cool wrapper classes like
Environment, our life becomes easy. But as soon as we start to feel lazy, the need for P/Invoke pops up (d-a-m-n!).
In a nutshell, P/Invoke (Platform Invoke) is Microsoft's way to get lazy, by not having to wrap all the Win32 APIs. This leaves, us, developers with some work to do. For example if you feel the need to share an Event between two processes (event is a named kernel object) you will be surprised (or not) to know that C# does not include this feature. For that reason, and many more, you need P/Invoke.
CreateEvent, Win API, as implemented in kernel32.dll:
C# P/Invoke code:
[DllImport("kernel32.dll, SetLastError=true ")]
static extern IntPtr CreateEvent(IntPtr lpEventAttributes,
bool bManualReset, bool bInitialState,
[MarshalAs(UnmanagedType.LPStr) string lpName);
As you can see you need to declare the exact prototype with the
static keyword (the only way to simulate a global method in C#), the
extern keyword (confess to the CLR that the method is not implemented in the assembly) and the
Hmmm… At this point you might think that this is not too bad, but, as you will soon witness, using P/Invoke can be a real pain.
Everything might go just well till you face the need to call a complex API that dazzles and puzzles you. "With what kinds of types should I declare the prototype? How to call the imported method? What to do when allocation is required? What to do with structures?"
For example, the
CreateFileMapping method (implemented in the kernel32.dll):
static extern IntPtr CreateFileMapping(IntPtr hFile,
IntPtr lpFileMappingAttributes, PageProtection flProtect,
uint dwMaximumSizeLow, string lpName);
MarshalAs whenever the P/Invoke type is different from the one that the API requires (see the
- The default marshaling type for strings in P/Invoke is
LPTSTR. If the actual parameter type differs from the P/Invoke default then you will need to use the
MarshalAs attribute in the function prototype declaration. For example, if a function receives the
LPCTSTR parameter then we should use
DllImport. This is important for strings. If the API works with Unicode and you don't use the auto attribute then the CLR will marshal the data as ANSI. For some reason Microsoft has decided not to use the auto attribute as default. The auto tells the CLR to figure out automatically what the preferred charset is.
- Performance considerations: "… P/Invoke has an overhead of between 10 and 30 x86 instructions per call. In addition to this fixed cost, marshaling creates additional overhead. There is no marshaling cost between blittable types that have the same representation in managed and unmanaged code. For example, there is no cost to translate between
Int32. For higher performance, it may be necessary to have fewer P/Invoke calls that marshal as much data as possible, rather than have more calls that marshal less data per call. Or somewhat more memorably: prefer a chunky over a chatty API."( MSDN).
- Make sure you use the
fixed keyword when passing managed allocation buffers to unmanaged code. When marshaling pointer to data, the garbage collector needs to be alerted not to mess with the allocated data, otherwise the unmanaged code might crash while trying to retrieve a corrupted memory addresses. The
fixed keyword tells the GC to leave your allocated data (PIN), and hence not to compact it during generating collections.
Unmanaged to Managed type translation table
StringBuilder [in, out]
Given the fact that in the current .NET framework (2.0 Beta) we still don't have wrappers for every Win32 API, using Platform Invoke (P/Invoke) is almost unavoidable.
You might not find all or exactly what you need from the above resources or from the entire article, but I am sure you will be able to learn from it and use what you have learned to find a solution to your needs. I encourage you to add your comments and promise to update the article periodically.