Tuesday, October 21, 2008

Signature/Data Type Conversion P/Invoke Cheat Sheet – aka What do you convert a wChar_t to .Net?

Just code - Tamir Khason - P/Invoke cheat sheet

“I’m working a lot with p/invoke, and know how it’s hard to produce correct signature for unmanaged method. So, today I decided to publish basic cheat sheet for methods, parameters and attributes you should use in order to invoke unmanaged methods from managed code without a lot of problems. We start with data type translations. Here the table to understand it.

Data type from unmanaged signature Data type in managed signature
int int

the same with all other simple types such as double, uint, etc or private objects
void* IntPtr
int* ref int
 

Unmanaged type Managed equivalent
bool bool
char sbyte (signed), byte (unsigned)
wchar_t char
double double
float single
int, long (signed) Int32
int, long (unsigned) UInt32
__int64 (signed) Int64
__int64 UInt64
short (signed) Int16
short (unsigned) UInt16
void void

But not only types are problem in managed/unmanaged transitions. Also structures are aligned differently. For this purpose we can use StructLayout attribute. Even if unmanaged classes are sequential and you used correct managed data types, you can find you with problems in Pack. What “pack” is? Pack is actually slot size in bytes for members of your structure. It can be 0, 1, 2, 4, 8, 16, 32, 64, or 128 and depends on the platform and application setting.

Now you can see, that it is not very complicated to create managed signatures when you have header of unmanaged assemblies. So go ahead and ask, if I missed something.

…” [Post Leach Level: 90%]

I was looking for something like this a while ago… Something to help me translate a third parties DLL/header file into P/Invoke signatures. Just a “data type conversion for work programmers (but not dummy)” and something like this would have really helped then.

No comments: