سؤال

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

هل كانت مفيدة؟

المحلول

As for the answer. You can't easily marshal an array with dynamic length. (although you can use SafeArray, see Marshal safearray of struct inside struct )

If you want to transfer objects over the wire, than it's not recommended to use marshalling in the first place. Use serialization for sending objects over the wire! Hint, look at protobuf-net by Marc Gravell for a very efficient serialization library.

Your code is faulted as well. You use UDP which can be a pain to begin with since it doesn't guarantee order and deliverability. You either have to define your own protocol which will take care of all of this, or simply rely on TCP/IP which inherently provides mechanisms to prevent these issues. Next to that, sockets are Stream based, not packet based. I really encourage you to do some googling on how to work with sockets

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top