Usefulness of bool* in C#

大兔子大兔子 提交于 2019-12-06 03:47:56

In C# you wouldn't normally use a bool*, which is something you can only use in unsafe code (which brings forth a whole lot of other stuff like pinning objects and so forth). A bool* would be a pointer to a boolean. A pointer is 4 bytes long and cannot be converted to a byte without loss.

Why would you want to do this and where do you encounter this? Normally, there's not easily a use case for using pointers in C# unless you have a very specific demand (i.e., an API call, but that you can solve using P/Invoke).

EDIT: (because you edited your q.)

The following code snippet shows you how to get the address of a boolean variable and how to convert that pointer to an int (converting to byte is not possible, we need four bytes).

unsafe
{
    // get pointer to boolean
    bool* boolptr = &mybool;                

    // get the int ptr (not necessary though, but makes following easier)
    int* intptr = (int*)boolptr;

    // get value the pointer is pointing at
    int myint = *intptr;

    // get the address as a normal integer
    int myptraddress = (int) intptr;
}

you say "ideally store 4 bits in a byte". Unless you have a 4-bits machine architecture, I'd strongly advice against it because it will make retrieving and storing the booleans very slow. But more importantly: you are talking C# here, not C++. C# is bound to the CLR which states that a boolean is stored as a byte and that each memory address is four bytes long in 32 bits architectures, which means pointers are four bytes long. Hence, your question, converting a bool* (pointer to a bool) to something else can only be converted into an integer or other datatype that is four bytes wide.

A tip: using flags you can utilize space best: this makes enum types take up a bit for each flag, which gives you eight booleans for each byte.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!