我想从应用于以下结构的StructLayout中获取22字节的结构大小。
[StructLayout(LayoutKind.Explicit, CharSet = CharSet.Ansi, Pack = 1, Size = 22)]
internal unsafe struct Entry
{
[FieldOffset(0)]
private fixed char title[14];
[FieldOffset(14)]
private readonly int size;
[FieldOffset(18)]
private readonly int start;
}有人会建议Marshal.SizeOf,但它返回的非托管对象的大小为28字节,这是不希望的。
int count = Marshal.SizeOf(typeof(Entry));但是,获取此属性似乎是不可能的,因为数组'customAttributes‘的长度始终为0。
var type = typeof(Entry);
var customAttributes = type.GetCustomAttributes(typeof(StructLayoutAttribute), true);有什么解决方法吗?
发布于 2013-07-17 02:56:35
StructLayout属性中的信息作为IL指令嵌入到方法中,而不是作为自定义属性。要检索它,可以使用Type.StructLayoutAttribute Property
var type = typeof(Entry);
var sla = type.StructLayoutAttribute;或者,如果结构在您的控制之下,您可以简单地定义一个大小常量:
[StructLayout(LayoutKind.Explicit, Pack = 1, Size = Entry.Size)]
internal unsafe struct Entry
{
public const int Size = 22;
...https://stackoverflow.com/questions/17684664
复制相似问题