本文介绍了在结构不正确对齐/非对象场的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用了如下定义为我的结构:

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:未能加载从组装​​式NetworkMessage',因为它包含一个对象字段偏移量5不正确地对齐或重叠由一个非对象字段

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?

任何帮助是非常AP preciated。

Any help is much appreciated.

谢谢,Venatu

Thanks,Venatu

编辑:道歉,我本来应该在我打算这是一种伪联盟更加明确。重叠的领域,是故意的,让我用一个结构为多种类型的消息,使得缓冲和绕过系统更容易。对不起,任何混乱

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 passing around the system easier. Sorry for any confusion

推荐答案

数组必须开始于4字节边界。

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/

又见Incorrectly通过一个非对象字段错误的对准或重叠的

这篇关于在结构不正确对齐/非对象场的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-31 00:19