C# 如何初始化固定字节数组?
我有以下结构:C# 如何初始化固定字节数组?,c#,bytearray,fixed,C#,Bytearray,Fixed,我有以下结构: [StructLayout(LayoutKind.Sequential, Pack = 1)] struct cAuthLogonChallenge { byte cmd; byte error; fixed byte name[4]; public cAuthLogonChallenge() { cmd = 0x04; error = 0x00; name = ??? } } n
[StructLayout(LayoutKind.Sequential, Pack = 1)]
struct cAuthLogonChallenge
{
byte cmd;
byte error;
fixed byte name[4];
public cAuthLogonChallenge()
{
cmd = 0x04;
error = 0x00;
name = ???
}
}
name
应该是一个以null结尾的ASCII字符串,Visual Studio拒绝接受我所有与之交互的想法。如何设置它?您需要切换到不安全模式才能使用固定语句
将结构定义更改为不安全结构…
,然后可以像在c/c++中一样初始化数组,明白了吗:
[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;
}
}
}
请记住,
*[a+b]
与C#/C++/C…)中的a[b]
相同,这意味着您可以将最后3行写成p[1]=。。。;p[2]=。。。;p[3]=代码>