开发者

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开发者_JAVA百科()
    {
        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?


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++


Got it:

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

    public cAuthLogonChallenge(byte dummy)
    {
        cmd = 0x04;
        error = 0x00;
        fixed (byte* p = this.name)
        {
            *p = (byte)'J';
            *(p + 1) = (byte)'o';
            *(p + 2) = (byte)'n';
            *(p + 3) = 0;
        }
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜