字节数组"Union"在C#StructLayout.Explicit中覆盖 [英] Byte Array "Union" overlay in c# StructLayout.Explicit

查看:52
本文介绍了字节数组"Union"在C#StructLayout.Explicit中覆盖的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在c#结构类型中使用一种c风格的uion.

I want to have a kind of c-style uion whithin a c# struct type.

由于某种原因,每次分配定义的类型时,都会出现异常. 这是我自己的类型.基本思想是我可以访问此结构的指针".不幸的是,我得到一个异常TypeLoadException:

For some reason i get an exception everytime I allocate a type that i defined. Here is my own type. The basic idea is that i have access to the "pointer" of this struct. Unfortunately i get an Exception TypeLoadException:

其他信息:无法从程序集"ManagedTarget,版本= 1.0.0.0,文化=中性,PublicKeyToken =空"中加载类型"ManagedTarget.FngPeriodeParameterType",因为它包含偏移量为0的对象字段,该对象字段被错误地对齐或重叠一个非对象字段.

Additional information: Could not load type 'ManagedTarget.FngPeriodeParameterType' from assembly 'ManagedTarget, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' because it contains an object field at offset 0 that is incorrectly aligned or overlapped by a non-object field.

怎么了?

[StructLayout(LayoutKind.Explicit, Size = 16)]
unsafe internal struct FngPeriodeParameterType
{
  [FieldOffset(0)]
  public Byte[] ByteArray;

  [FieldOffset(0)]
  public UInt32 Repetitions;

  [FieldOffset(4)]
  public Int16 Amplitude;

  [FieldOffset(6)]
  public Int16 Offset;

  [FieldOffset(8)]
  public Int16 Gain;

  [FieldOffset(10)]
  public UInt16 Selection;

  [FieldOffset(12)]
  public UInt32 Step;
}

推荐答案

如果您的意图是ByteArray是原始数据,则它必须是fixed缓冲区;目前,它只是对堆上不相关 byte[]的引用-您不能将引用和uint重叠:

If your intent is that ByteArray is the raw data, it must be a fixed buffer; at the moment, it is simply a reference to an unrelated byte[] on the heap - and you can't overlap a reference and a uint:

[FieldOffset(0)]
public fixed byte ByteArray[16];

但是,使用它可能会很痛苦.我通常会添加以下辅助方法:

Working with it can be a pain, though; I usually add helper methods like:

public void ReadBytes(byte[] data)
{
    fixed (byte* ptr = ByteArray)
    {
        for (int i = 0; i < 16; i++)
            data[i] = ptr[i];
    }
}

这篇关于字节数组"Union"在C#StructLayout.Explicit中覆盖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆