我创建了 2 个简单的控制台程序和一个简单的结构。
M11 对象是我们要通过网络发送的测试对象。
using System.Runtime.InteropServices;
using System;
namespace MessageInfo
{
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct M11
{
/// <summary>
/// Message Header
/// </summary>
public MessageHeader MessageHeader;
[MarshalAs(UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_I2)]
public short[] ArrayOfNumber;
}
/// <summary>
/// Message Header
/// </summary>
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct MessageHeader
{
public byte mType;
public ulong mId;
}
}
SimpleSender 将编组对象并通过网络发送。
static void Main(string[] args)
{
int m11Size = 0;
M11 m11Structure = new M11();
MessageHeader header = new MessageHeader();
header.mType = 0x01;
header.mId = Convert.ToUInt64(DateTime.Now.ToString("yyyyMMddHHmmssfff"));
m11Size += Marshal.SizeOf(header);
m11Structure.MessageHeader = header;
short[] arrayOfNumber = new short[5] { 5, 4, 3, 2, 1 };
m11Structure.ArrayOfNumber = arrayOfNumber;
m11Size += Marshal.SizeOf(typeof(ushort)) * arrayOfNumber.Length;
byte[] m11Bytes = new byte[m11Size];
GCHandle m11Handler = GCHandle.Alloc(m11Bytes, GCHandleType.Pinned);
try
{
IntPtr m11Ptr = m11Handler.AddrOfPinnedObject();
Marshal.StructureToPtr(m11Structure, m11Ptr, false);
using (Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
{
try
{
IPEndPoint iep = new IPEndPoint(IPAddress.Parse("192.168.2.110"), 3000);
sock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
sock.SendTo(m11Bytes, iep);
}
finally
{
sock.Close();
}
}
}
catch (Exception ex) { Console.Write(ex.ToString()); }
finally { m11Handler.Free(); }
Console.ReadLine();
}
最后但同样重要的是,接收者将接收字节并转换为对象。
static void Main(string[] args)
{
M11 m11Structure = new M11();
using (UdpClient udpClient = new UdpClient(3000))
{
try
{
IPEndPoint ep = new IPEndPoint(IPAddress.Parse("192.168.2.110"), 3000);
byte[] m11Bytes = udpClient.Receive(ref ep);
GCHandle m11Handler = GCHandle.Alloc(m11Bytes, GCHandleType.Pinned);
try
{
IntPtr m11Ptr = m11Handler.AddrOfPinnedObject();
m11Structure = (M11)Marshal.PtrToStructure(m11Ptr, typeof(M11));
PrintM11Structure(m11Structure);
}
catch (Exception ex) { Console.WriteLine(ex.ToString()); }
finally { m11Handler.Free(); }
}
finally { udpClient.Close(); }
}
Console.ReadLine();
}
问题是接收程序在调用 Marshal.PtrToStructure 时总是抛出“System.AccessViolationException: Attempted to read or write protected memory”。
需要注意的几点: 1. 它只适用于 MessageHeader。2. ushort 数组具有动态大小。
提前致谢。
亨利