Struct fra byte array
Hej eksperterJeg modtager et byte array fra en UDP klient, som skal konverteres til en Struct, som blandt andet også indeholder et byte array.
For at konvertere mellem de to bruger jeg pointere, men jeg bliver ved med at få fejl på grund af byte arrayet i min struct.
Fejlen: Cannot marshal field 'Data' of type 'ArtnetMediaControl.ArtNetPacket': Invalid managed/unmanaged type combination (this value type must be paired with Struct).
Kode:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace ArtnetMediaControl
{
[StructLayout(LayoutKind.Explicit, Size = 530, Pack = 1, CharSet = CharSet.Ansi)]
public unsafe struct ArtNetPacket
{
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 8)]
[FieldOffset(0)]
public string Name; // always "Art-Net"0
[MarshalAs(UnmanagedType.U2)]
[FieldOffset(8)]
public ushort Opcode; // 0x5000
[MarshalAs(UnmanagedType.U2)]
[FieldOffset(10)]
public ushort ProtocolVersion; // 14
[MarshalAs(UnmanagedType.U1)]
[FieldOffset(12)]
public byte Sequence;
[MarshalAs(UnmanagedType.U1)]
[FieldOffset(13)]
public byte Physical;
[MarshalAs(UnmanagedType.U2)]
[FieldOffset(14)]
public ushort Universe;
[MarshalAs(UnmanagedType.U2)]
[FieldOffset(16)]
public ushort Length; // mostly 512
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 512, ArraySubType = UnmanagedType.U1)]
[FieldOffset(18)]
public unsafe fixed byte Data[512]; // DEN HER LAVER FEJL
}
public class ArtnetServer
{
private IPAddress Ip;
private int Port;
public ArtnetServer(IPAddress ip, int port)
{
Ip = ip;
Port = port;
}
public void Listen()
{
IPEndPoint listenerIp = new IPEndPoint(Ip, Port);
UdpClient socket = new UdpClient(listenerIp);
IPEndPoint senderIp = new IPEndPoint(IPAddress.Any, 0);
byte[] data;
System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("en-US");
while (true)
{
data = socket.Receive(ref senderIp);
GCHandle handle = GCHandle.Alloc(data, GCHandleType.Pinned);
unsafe
{
ArtNetPacket packet = (ArtNetPacket)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(ArtNetPacket)); // FEJLEN SKER HER
}
handle.Free();
}
}
}
}
Nogle gode bud?
//hermandsen