开发者

Incorrectly-aligned/non-object field in struct

开发者 https://www.devze.com 2023-03-25 10:53 出处:网络
I am using the following definition for my struct: [StructLayout(LayoutKind.Explicit)] public struct NetworkMessage

I am using the following definition for my struct:

[StructLayout(LayoutKind.Explicit)]
public struct NetworkMessage
{

    [FieldOffset(0)]
    public MessageType Type;
    [FieldOffset(4)]
    public bool GatewayMessage;               

    //AuthenticationRequest
    [FieldOffset(5)]
    public char[] AuthenticationUsername; //20 charachters long
    [FieldOffset(13)]
    public byte[] AuthenticationPasswordHash; // 16 bytes long

    //Authntication result
    [FieldOffset(5)]
    public bool AuthenticationSuccess;
    [FieldOffset(6)]
    public char[] AuthenticationMessage;
}

However, when I attempt to use this type, I get this error message:

System.TypeLoadException: Could not load type 'NetworkMessage' from assembly because it contains an object field at offset 5 that is incorrectly aligned or overlapped by a non-object field.

Does non-object field mean how one is a value, and one is a reference? Can I not mix these?

Any help is much appreciated.

Thanks, Venatu

EDIT: Apologies, I should have been more explicit in that I am intending this as a kind of pseudo-union. The overlap is fields is intentional to allow me to use one struct as a multiple types of messages, making buffering and p开发者_StackOverflowassing around the system easier. Sorry for any confusion


Arrays must start on 4-byte boundaries.

See this article for more information on using arrays in explicit structs. It also mentions the even boundary issue for arrays, and describes some alternative options for arrays in explicit structs.

http://www.developerfusion.com/article/84519/mastering-structs-in-c/

see also Incorrectly aligned or overlapped by a non-object field error

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号