Search code examples
c#arraysfixed

How do I initialize a fixed byte array?


I have the following struct:

[StructLayout(LayoutKind.Sequential, Pack = 1)]
struct cAuthLogonChallenge
{
    byte cmd;
    byte error;
    fixed byte name[4];

    public cAuthLogonChallenge()
    {
        cmd = 0x04;
        error = 0x00;
        name = ???
    }
}

name is supposed to be a null-terminated ASCII string, and Visual Studio is rejecting all my ideas to interact with it. How do I set it?


Solution

  • You need to switch to unsafe mode to use fixed statement

    http://msdn.microsoft.com/en-us/library/f58wzh21%28v=VS.80%29.aspx

    http://msdn.microsoft.com/en-us/library/chfa2zb8%28v=VS.80%29.aspx

    http://msdn.microsoft.com/en-us/library/zycewsya%28v=VS.80%29.aspx

    Change your struct definition to unsafe struct ... then you can initialize your array like in c/c++