Matthew Layton
Matthew Layton

Reputation: 42260

Mapping Windows Data Types to .NET

I have just been looking through the list of Windows Data Types as I am trying to work out how each type maps to it's equivalent .NET type.

I noticed that some of the type definitions are surrounded by #if tags, which changes their definition based upon the platform.

For example, here is the definition for INT_PTR

#if defined(_WIN64) 
 typedef __int64 INT_PTR; 
#else 
 typedef int INT_PTR;
#endif

My understanding is that this creates a 64bit INT_PTR on 64bit machines, and a 32bit INT_PTR on 32bit machines. Okay....NET does the same thing in this respect as IntPtr and UIntPtr are platform specific, and therefore adapt between 32bit and 64bit machines.

Now, lets consider LONGLONG

#if !defined(_M_IX86)
 typedef __int64 LONGLONG; 
#else
 typedef double LONGLONG;
#endif

So in .NET my assumption is that this maps to Int64 (long) ?

Also, consider TCHAR

#ifdef UNICODE
 typedef WCHAR TCHAR;
#else
 typedef char TCHAR;
#endif

My assumption here is that this maps to char (since .NET's char is unicode anyway)?

Questions:

  1. If a native type is platform dependent, should it's .NET equivalent be the larger of the two definitions?
  2. Are there any known pitfalls when mapping data types?

Upvotes: 0

Views: 1383

Answers (1)

Jim Mischel
Jim Mischel

Reputation: 133995

Check out Platform Invoke Data Types.

There are many pitfalls when mapping data types. For example, the difference between the Windows data types BOOL and Boolean. The default marshaling for the .NET Boolean data type (C# bool) will marshal it as a 32-bit integer to match the Windows BOOL type. The Windows Boolean data type is one byte. If you want to pass a C# bool to a Windows Boolean, you have to specify custom marshaling.

Structure packing can trip you up, and marshaling arrays can be very tricky, especially arrays inside structures.

You definitely want to read Marshaling Data with Platform Invoke very carefully.

Upvotes: 1

Related Questions