如何在 C# 中声明一个包含固定数量固定大小字符串的数组?

How to declare an array with a fixed number of fixed-sized strings in C#?

基本上我需要的是一个字符串数组,其中数组有 4 个元素,每个字符串正好是 16 个字节。

目前我正在使用这个:

[StructLayout(LayoutKind.Sequential, Pack = 8)]
public struct SomeStruct
{
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 16)]
    public string string1; // 16 Byte String

    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 16)]
    public string string2; // 16 Byte String

    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 16)]
    public string string3; // 16 Byte String

    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 16)]
    public string string4; // 16 Byte String
}

但是我想要的是这样的:

[StructLayout(LayoutKind.Sequential, Pack = 8)]
public struct SomeStruct
{
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 16)]
    public string[4] strings; // 4 times 16 Byte String

}

我知道你也可以使用 MarshalAs 来固定数组的大小:

    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
    private byte[] bytes;            // 4 Byte

我怎样才能达到我所需要的?

重要的是大小不要以任何方式改变,因为我收到一个包含我的结构数据的字节[],所以改变大小或顺序会弄乱一切。

在尝试了一些事情之后,我找到了解决我的问题的方法(或者至少是一个可接受的解决方法)。我将结构更改为 class 并实现了一些额外的方法:

[StructLayout(LayoutKind.Sequential, Pack = 8)]
public class SomeClass
{
    public string[] strings()
    {
        string[] strs = new string[4];
        strs[0] = string1;
        strs[1] = string2;
        strs[2] = string3;
        strs[3] = string4;
    }

    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 16)]
    public string string1; // 16 Byte String

    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 16)]
    public string string2; // 16 Byte String

    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 16)]
    public string string3; // 16 Byte String

    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 16)]
    public string string4; // 16 Byte String
}

对于其他数据类型要容易得多,例如我需要我的布尔值是 1 个字节而不是默认的 4 个字节:

[StructLayout(LayoutKind.Sequential, Pack = 8)]
public class SomeClass
{

    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 8, ArraySubType = UnmanagedType.I1)]
    public bool[] bs; // 8 times 1 Byte boolean

}

SizeConst定义数组元素的个数,而ArraySubType可用于定义数组数据类型。