[英]Use Win32API: unions within structures generate TypeLoadException
[英]Unions of fixed size structures for use in safe context
我正在处理可以以字节数组形式接收或发送的数据包,该数据包具有固定的结构。 因此,我正在尝试创建一个有效的联合,如下所示:
using System; // etc..
namespace WindowsApplication1
{
public partial class Main : Form
{
public const int PktMaxSize = 124;
// ...etc..
// ...will use Pkt structure below...
}
[System.Runtime.InteropServices.StructLayout(LayoutKind.Explicit)]
public struct Pkt
{
[System.Runtime.InteropServices.FieldOffset(0)]
fixed Byte bytes[Main.PktMaxSize]; // complete byte pkt
[System.Runtime.InteropServices.FieldOffset(0)]
fixed Byte PktID[8];
[System.Runtime.InteropServices.FieldOffset(8)]
UInt16 Properties;
// ...etc..
}
}
我收到C#错误
指针和大小缓冲区只能在不安全的上下文中使用
为了能够在安全的环境中创建和使用“不安全的”结构,我需要做什么?
感谢您的帮助-公开有关如何处理可轻松与C ++互操作类接收(或发送)的固定字节流进行转换的数据包结构的任何建议。
使用fixed
关键字要求Pkt
及其使用的所有方法都必须声明为不安全,例如,
[StructLayout(LayoutKind.Explicit)]
public unsafe struct Pkt
{
[FieldOffset(0)]
fixed Byte bytes[124];
...
}
如果您不想使用不安全的代码,则可以如下声明Pkt
:
[StructLayout(LayoutKind.Explicit)]
public struct Pkt
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 124)]
[FieldOffset(0)]
Byte[] bytes;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)]
[FieldOffset(0)]
Byte[] PktID;
[FieldOffset(8)]
UInt16 Properties;
}
在方法或块上使用unsafe关键字:
unsafe static void DoSomethingUnsafe()
{
// use Pkt structure
}
static void DoSomething()
{
// do safe things
unsafe
{
// use Pkt structure
}
}
您还必须通过/ unsafe选项或Visual Studio中的“项目”>“属性”>“生成”选项卡来启用不安全代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.