简体   繁体   English

用C#中的非原始类型重新创建C ++联合类型的对齐错误

[英]Alignment error recreating C++ union type with non-primitive types in C#

I have a simple union (byte array and a short) in C++ which I am attempting to port to C# and getting Could not load type ... Union ... because it contains an object field at offset 0 that is incorrectly aligned or overlapped by a non-object field. 我在C ++中有一个简单的联合体(字节数组和一个短整数),试图将其移植到C#并Could not load type ... Union ... because it contains an object field at offset 0 that is incorrectly aligned or overlapped by a non-object field.联合体Could not load type ... Union ... because it contains an object field at offset 0 that is incorrectly aligned or overlapped by a non-object field. I suspect that my implementation doesn't work because I have array as one of the struct members. 我怀疑我的实现无法正常工作,因为我将数组作为结构成员之一。

existing C++ union: 现有的C ++联合:

union {
    char    c[2];
    short        data;
} u;

attempted C# implementation: 尝试C#实现:

[StructLayout(LayoutKind.Explicit, Size =2)]
public struct Union
{
    [MarshalAs(UnmanagedType.LPArray)]
    [FieldOffset(0)]
    public byte[] c;
    [FieldOffset(0)]
    public short data;
}

similar question was answered before but it seems to work only for primitive types: C++ union in C# 之前回答过类似的问题,但它似乎仅适用于原始类型: C#中的C ++联合

Thank you in advance. 先感谢您。

Have you tried "StructLayout(LayoutKind.Explicit, Size =2, Pack=1)"? 您是否尝试过“ StructLayout(LayoutKind.Explicit,Size = 2,Pack = 1)”? Seems to be a problem with C# default to a 4-byte packing size. C#似乎有问题,默认为4字节打包大小。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 C# 对象初始化程序将初始化只读属性,但仅适用于非原始类型 - C# object initializer will initialize read only properties, but for non-primitive types only 在C#中将具有非原始数据的对象固定 - pin an object with non-primitive data in c# 图表绑定到非基本类型 - Chart bind to non-primitive type Json反序列化和使用c#和ASP.NET MVC和JSON.NET打印非原始对象 - Json Deserialization and printing non-primitive object using c# and ASP.NET MVC and JSON.NET 在C#中将字节数组转换为具有未知类型的原始类型的数组 - Converting a byte array to an array of primitive types with unknown type in C# 是否将C#类型参数约束为一系列原始类型? - Constraining a C# type parameter to a series of primitive types? Linq to Entities:如何使用非原始类型进行过滤 - Linq to Entities: how to filter using Non-Primitive types C#预定义类型与原始类型? - C# predefined types vs primitive types? protocol-buffers序列化,包含大量非基本类型 - protocol-buffers serialization with large list of non-primitive types 配置ReSharper只是为非基本类型推荐`var`? - Configure ReSharper only to recommend `var` for non-primitive types?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM