Bookmark and Share

Tuesday, October 13, 2009

Convert c++ bool to .NET bool

Be careful when you work with Interop and you call functions written in C++ returning bool.
In c++ the bool type is managed with one byte, in .Net Framework the bool type is managed with 4bytes(32bit).

So if you have a c++ api like this:

extern "C" bool GetBoolStatusFromC();

and a definition in the c# code like this:

[DllImport("myOldCpp.dll", CharSet = CharSet.Unicode)]
extern public static bool GetBoolStatusFromC();

You could have strange results, sometimes you receive true sometimes you receive false without a clear logic.

When the C++ bool is returned it is stored with one byte in AL and it is mapped to the EAX registy that is 4 bytes replacing only the last byte.
The other 24 bits remains dirty and they should contains values from other system calls that works with the EAX register.
So, the dirty 24 bytes causes random C# bool values, without control.

The solution is:

- decorate the PInvoke declaration with [return:MarshalAs(UnmanagedType.I1)]
- change the c++ declaration and use INT as return value.

Hope it helps,