简体   繁体   English

如何初始化固定字节数组?

[英]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. name应该是一个以空值结尾的ASCII字符串,Visual Studio拒绝了我所有与之交互的想法。 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/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/chfa2zb8%28v=VS.80%29.aspx

http://msdn.microsoft.com/en-us/library/zycewsya%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++ 将您的结构定义更改为unsafe struct ...然后可以像在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;
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM