I created 2 simple console program and a simple structure.
M11 Object is the test object that we want to send across network.
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;
}
}
And SimpleSender will Marshal the object and send across the network.
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();
}
Last but not least, the receiver that will receive the bytes and convert to the object.
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();
}
The problem is the receiver program always throw "System.AccessViolationException: Attempted to read or write protected memory" when it called Marshal.PtrToStructure.
Few things to note: 1. It works fine with only MessageHeader. 2. And ushort array has dynamic size.
Thanks in advance.
Henri