chrisdill / raylib-cs

C# bindings for raylib, a simple and easy-to-use library to learn videogames programming

Home Page:http://www.raylib.com/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Do we really need CBool?

Auios opened this issue · comments

commented

What is CBool and why do we use it?

CBool comes from this here:

public readonly struct CBool

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:

public static extern CBool IsKeyPressed(KeyboardKey key);

[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.