C
C#4mo ago
Nolram

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++:
bool sb_IsKeyDown(int key)
{
return keyboardState[key];
}
bool sb_IsKeyDown(int key)
{
return keyboardState[key];
}
C#:
[DllImport(DLL_NAME, CallingConvention = CallingConvention.Cdecl)]
private static extern bool sb_IsKeyDown(int key); // Returns true when it shouldn't in Release builds.
[DllImport(DLL_NAME, CallingConvention = CallingConvention.Cdecl)]
private static extern bool sb_IsKeyDown(int key); // Returns true when it shouldn't in Release builds.
Please ping me on reply, thank you!
9 Replies
reflectronic
reflectronic4mo ago
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)]
Nolram
NolramOP4mo ago
Oh are native bools and managed bools not the same data?
reflectronic
reflectronic4mo ago
no, it's because by default bool is marshaled as the Win32 struct BOOL which is 4 bytes
Nolram
NolramOP4mo ago
Ohhh yeah that makes sense... I keep forgetting the C ABI has no concept of a bool
reflectronic
reflectronic4mo ago
bool did not exist in C in 1985
Nolram
NolramOP4mo ago
Yeah that makes sense actually, not sure why I didn't anticipate that
reflectronic
reflectronic4mo ago
and someone chose to implement it as typedef int BOOL; and that's how it has been since
Nolram
NolramOP4mo ago
I see - thank you for the help and apologies for my stupidity.
Petris
Petris4mo ago
someone at MS that is
Want results from more Discord servers?
Add your server