Do we really need CBool?
Auios opened this issue · comments
What is CBool
and why do we use it?
CBool
comes from this here:
using System.Runtime.InteropServices;
namespace Types;
[StructLayout(LayoutKind.Sequential)]
public readonly struct CBool {
private readonly byte value;
private CBool(bool value) {
this.value = Convert.ToByte(value);
}
public static implicit operator CBool(bool value) {
return new CBool(value);
}
public static implicit operator bool(CBool x) {
return Convert.ToBoolean(x.value);
}
public override string ToString() {
return Convert.ToBoolean(this.value).ToString();
}
}
It's being used for things like this:
Raylib-cs/Raylib-cs/interop/Raylib.cs
Line 649 in a545ce3
[DllImport(nativeLibName, CallingConvention = CallingConvention.Cdecl)]
public static extern CBool IsKeyPressed(KeyboardKey key);
Why not use native bool
instead?
I tried using bool
instead of CBool
and it's always true
. Alright, I made it an int
instead and I see now. It's int
value is 256
when false
and 257
when true.
Or when read in binary, 100000000
for false
and 100000001
for true
.
Do we really need CBool?
According to this SO post: https://stackoverflow.com/questions/37809854/why-does-my-dllimport-function-always-return-true
We could just use [return:MarshalAs(UnmanagedType.I1)]
. I've tested this and it works.
public static class Keyboard {
[DllImport("raylib", CallingConvention = CallingConvention.Cdecl, EntryPoint = "IsKeyDown")]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool IsKeyDown(KeyboardKey key);
}
Now we can use native C# bool
instead of CBool
.
I used MarshalAs initially but changed to use CBool so users can choose if they want to convert the value to a bool or access the value directly.