Click here to Skip to main content
Click here to Skip to main content

Essential P/Invoke

, 31 Oct 2005
Rate this:
Please Sign up or sign in to vote.
The article aims to shed some light on an irksome topic, in managed code, named P/Invoke.

Introduction

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.

Lazy development

Working in a managed environment like the .NET Framework is fun. With cool wrapper classes like Thread and 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:

HANDLE CreateEvent(
  LPSECURITY_ATTRIBUTES lpEventAttributes,
  BOOL bManualReset,
  BOOL bInitialState,
  LPCTSTR lpName
);

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 DllImport attribute.

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):

HANDLE CreateFileMapping(
  HANDLE hFile,
  LPSECURITY_ATTRIBUTES lpAttributes,
  DWORD flProtect,
  DWORD dwMaximumSizeHigh,
  DWORD dwMaximumSizeLow,
  LPCTSTR lpName
); 


[DllImport("kernel32.dll", SetLastError=true)]
static extern IntPtr CreateFileMapping(IntPtr hFile,
   IntPtr lpFileMappingAttributes, PageProtection flProtect, 
   uint dwMaximumSizeHigh,
   uint dwMaximumSizeLow, string lpName);

Tips

  • Use MarshalAs whenever the P/Invoke type is different from the one that the API requires (see the CreateEvent example).
  • 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 [MarshalAs(UnmanagedType.LPTStr)] strings.
  • Use CharSet.Auto in 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 int and 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

C/C++ C#
HANDLE, LPDWORD, LPVOID, void* IntPtr
LPCTSTR, LPCTSTR, LPSTR, char*, const char*, Wchar_t*, LPWSTR String [in], StringBuilder [in, out]
DWORD, unsigned long, Ulong UInt32, [MarshalAs(UnmanagedType.U4)]
bool bool
LP<struct> [In] ref <struct>
SIZE_T uint
LPDWORD out uint
LPTSTR [Out] StringBuilder
PULARGE_INTEGER out ulong
WORD uInt16
Byte, unsigned char byte
Short Int16
Long, int Int32
float single
double double
NULL pointer IntPtr.Zero
Uint Uint32

Resources

Epilogue

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.

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

Share

About the Author

No Biography provided

Comments and Discussions

 
GeneralCalling C++ dll by using C# wrapper method PinmemberAshoka the Great23-Mar-10 6:25 
AnswerRe: Calling C++ dll by using C# wrapper method PinmemberShawn-USA5-Jun-13 9:19 
QuestionP/Invoke & Environment problem? Pinmemberfergara18-Sep-08 12:32 
General32 64 bit Pinmemberhahnl8-Sep-07 6:05 
GeneralRe: 32 64 bit PinmemberShawn-USA5-Jun-13 9:31 
Here are the list of issues when P/Invoke are involved with 32 bits and 64 bits you may be interested in looking.
 
1. storage size difference of class.
2. storage size difference of struct.
3. Parameter difference, such as size_t used in C++.
4. Size difference of pointer.
5. Call stack difference, calling convention.
 
etc.

QuestionHow to translate "const std::string" PinmemberLorenz C5-Jun-07 6:07 
AnswerRe: How to translate "const std::string" PinmemberCohen Shwartz Oren8-Jun-07 13:44 
GeneralRe: How to translate "const std::string" PinmemberShawn-USA5-Jun-13 9:26 
Generalgood job and thanks PinmemberJames Ashley8-May-07 8:15 
GeneralRe: good job and thanks PinmemberCohen Shwartz Oren8-Jun-07 13:46 
QuestionLPDWORD PinmemberJonathan L. Nazario13-Mar-07 14:11 
AnswerRe: LPDWORD PinmemberCohen Shwartz Oren13-Mar-07 15:07 
QuestionHow get the DNS Domain name using PInvoke? PinmemberCohen Shwartz Oren6-Feb-07 0:24 
AnswerRe: How get the DNS Domain name using PInvoke? PinmemberCohen Shwartz Oren6-Feb-07 0:24 
GeneralNice PinmemberS.B.8-Nov-05 11:18 
GeneralRe: Nice PinmemberCohen Shwartz Oren13-Mar-07 15:07 

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.141216.1 | Last Updated 31 Oct 2005
Article Copyright 2005 by Cohen Shwartz Oren
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid