联合体内具有引用类型和值类型成员的封送处理结构 [英] Marshaling structure with reference-type and value-type members inside a union
问题描述
bellow代码是本机win32代码的编组. 但是我收到一条错误消息
bellow code is the marshling of a native win32 code. but i get an error message
类型加载异常,无法从程序集中加载,因为它包含偏移量为0的对象字段,该对象字段与非对象字段错误地对齐或重叠
存在一个同时具有value-type
成员和reference-type
的结构S1.该结构是必须具有fieldOffset的并集成员,但是所有S1成员不能从fieldOffset 0开始,它们是引用和值类型...我该如何处理?
there is a structure S1 with both value-type
member and reference-type
.. this structure is a member of union which has to have fieldOffset, but all S1 members can not start from fieldOffset 0 they are a mixture of reference and value type...how can I handle that??
[StructLayout(LayoutKind.Sequential)]
public struct S1
{
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = Const.FieldSizeMsgid + 1)]//Reference Type
public String MsgId;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = Const.FieldSizeTime + 1)]//Reference Type
public String SendTime;
public UInt32 SubsSeq;//Value Type
public UInt32 ServTime;//Value Type
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = Const.FieldSizeFillerA1 + 1)]//Reference Type
public String Filler;
}
[StructLayout(LayoutKind.Explicit)]
public struct AdminData
{
[FieldOffset(0)] public S1 S11;// get an error because the S1 has both reference type member and value type member
[FieldOffset(0)] public S2 S22;
[FieldOffset(0)] public S3 S33;
}
我知道我必须将S1分成2个结构,一个结构具有值类型成员,另一个结构具有引用类型成员..但是我不知道该如何做以及如何在AdminData中引用它们.工会.
I know I have to break the S1 into 2 structures, one with value-type members and the other for reference-type members..but I do not know how to do it and how to reference them in AdminData which is a union.
编辑:
这是c ++代码
typedef struct S1
{
char MsgId [Const.FieldSizeMsgid + 1];//Reference Type
char SendTime[Const.FieldSizeTime + 1];//Reference Type
int SubsSeq;//Value Type
int ServTime;//Value Type
char Filler[Const.FieldSizeFillerA1 + 1];//Reference Type
}
union AdminData
{
S1 S11;//has both value type member and reference type member
S2 S22;//has both value type member and reference type member
S3 S33;//has both value type member and reference type member
}
typedef struct MMTPMsg
{
int Length;
short Type;
AdminData Data; //the union
long long TimeStamp;
}
推荐答案
如您所知,您不能将引用类型覆盖在值类型之上.因此,要实现您的联合,您需要使用其中之一.您的结构必须包含值类型,因此我们得出结论,您必须仅使用值类型.
As you have discovered you cannot overlay reference types on top of value types. So to implement your union, you need to use either one or the other. Your structures must contain value types and so we conclude that you must use value types exclusively.
那么,如何将字符数组实现为值类型?通过使用固定大小的缓冲区.
So, how do you implement your character arrays as value types? By using a fixed size buffer.
unsafe public struct S1
{
fixed byte MsgId[Const.FieldSizeTime + 1];
....
}
这篇关于联合体内具有引用类型和值类型成员的封送处理结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!