在 C# 中使用 StructLayout 联合 [英] Union in c# with StructLayout
本文介绍了在 C# 中使用 StructLayout 联合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有多个结构体,它们都以一个头结构体开始.像这样
I have multiple structs that all starts with a header struct. Like this
public struct BaseProtocol {
public Header header;
public Footer footer;
};
标题是
public struct Header {
public Byte start;
public Byte group;
public Byte dest;
public Byte source;
public Byte code;
public Byte status;
};
现在的问题是我需要将它们与 Byte[] 联合起来.我用这个试过了
The problem now is that I need to union them with a Byte[]. I tried it with this
[StructLayout( LayoutKind.Explicit, Size=255 )]
public struct RecBuffer {
[FieldOffset( 0 )]
public Header header;
[FieldOffset( 0 )]
[MarshalAs( UnmanagedType.ByValArray, ArraySubType = UnmanagedType.I1, SizeConst = 255 )]
public Byte[] buffer;
};
当我用数据填充缓冲区时,我无法从标题中获取数据.如何让 c# 像在 c++ 中使用 union 一样?
When I fill the buffer with data I can't get the data from the header. How can I make c# do the same as I can do with union in c++?
推荐答案
Byte[] 是引用类型字段,不能与值类型字段叠加.您需要一个固定大小的缓冲区,并且需要使用 /unsafe
编译它.像这样:
Byte[] is a reference type field, which you cannot overlay with a value type field. You need a fixed size buffer and you need to compile it with /unsafe
. Like this:
[StructLayout(LayoutKind.Explicit, Size = 255)]
public unsafe struct RecBuffer
{
[FieldOffset(0)]
public long header;
[FieldOffset(0)]
[MarshalAs(UnmanagedType.ByValArray, ArraySubType = UnmanagedType.I1, SizeConst = 255)]
public fixed Byte buffer[255];
};
这篇关于在 C# 中使用 StructLayout 联合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文