August 17, 2008

PInvoke, managed and unmanaged datatypes

I'm doing a lot of PInvoking lately. One of the hard parts is mapping the unmanaged datatypes found in c++ include files to managed datatypes.

I found a nice article on codeproject with a list of the most common mappings. I'll repeat the list here so I can find it easilly, maybe other people can benefit from it too. I'll keep the list up-to-date with my own mappings and some remarks.

Unmanaged Managed Remarks
BOOL, BOOLEAN Boolean, Int32 A 32 bit field set to 0 for FALSE and 1 for TRUE
BSTR String  
BYTE SByte Signed byte, the original article has BYTE and UBYTE switched around.
CHAR Char CHAR is single byte ANSI character, Char is a dual byte Unicode character. Byte may be a better mapping.
DOUBLE Double  
DWORD UInt32 The original article also said Int32, but DWORD is always unsigned
FLOAT Single  
GUID Guid GUID is actually a c struct consisting of different integer values. The framework marshalls this to a Guid value.
HANDLE IntPtr 32 bits on x86, 64 bits on 64 bit platforms.
Also used for other handles like HFONT and HMENU
HRESULT Int32 The original artilcle also said UInt32 but HRESULT is defined as signed
INT Int32  
LANGID Int16 or UInt16  
LCID Int32 or UInt32  
LONG Int32  
LPARAM IntPtr, UIntPtr or Object Value can represent different things depending on context. 32 or 64 bits depending on platform.
LPCSTR, LPCTSTR, LPCWSTR String  
LPSTR, LPTSTR, LPWSTR String String is immutable so use StringBuilder instead of String if the string can change in unmanaged code
LPVOID IntPtr, UIntPtr or Object  
LRESULT IntPtr Value can represent different things depending on context. 32 or 64 bits depending on platform.
SAFEARRAY .NET array type  
SHORT Int16  
TCHAR Char  
UCHAR Byte  
UINT UInt32  
ULONG UInt32  
UUID Guid Not sure if this works. GUID and UUID datatype are about the same so it should.
VARIANT Object  
VARIANT_BOOL Boolean  
WCHAR Char 16 bit Unicode character
WORD UInt16 The original article also said Int32 but WORD is unsigned only.
WPARAM IntPtr, UIntPtr or Object Value can represent different things depending on context. 32 or 64 bits depending on platform.

Most of the unmanaged datatypes are defined in windef.h. Microsoft has a page on MSDN here with descriptions.

No comments:

Post a Comment