P/Invoke boolean call always returns true in Release builds
I have a simple boolean function in a native C++ DLL (for keyboard input in my case), which I P/Invoke from C#.
In debug builds, everything works fine.
But in a release build (of both the C# and C++ projects), the C# side always receives true from the P/Invoke call, even when the native side returns false.
I've checked my build settings but I can't figure out what is happening here- any recommendations for how to debug this or what could be the potential cause?
For reference - my code looks a little bit something like this:
C++:
C#:
Please ping me on reply, thank you!
9 Replies
you are not marshalling the bool correctly
bool
in a P/Invoke is a 4 byte bool
this means that whatever garbage is left in the upper bits of the return register can cause the marshaller to treat it as true
use [return: MarshalAs(UnmanagedType.I1)]
Oh are native bools and managed bools not the same data?
no, it's because by default
bool
is marshaled as the Win32 struct BOOL
which is 4 bytesOhhh yeah that makes sense... I keep forgetting the C ABI has no concept of a bool
bool
did not exist in C in 1985Yeah that makes sense actually, not sure why I didn't anticipate that
and someone chose to implement it as
typedef int BOOL;
and that's how it has been sinceI see - thank you for the help and apologies for my stupidity.
someone at MS that is