I'm creating a networked application. For this I'm creating a messaging system. What I've got so far (a snippet at least...)
public static byte[] ClassToBytes(GenericMessage Data)
{
int Size = Marshal.SizeOf(Data);
byte[] Buffer = new byte[Size];
IntPtr Ptr = Marshal.AllocHGlobal(Size);
Marshal.StructureToPtr(Data, Ptr, true);
Marshal.Copy(Ptr, Buffer, 0, Size);
Marshal.FreeHGlobal(Ptr);
return Buffer;
}
public static GenericMessage BytesToClass(byte[] Source, ClassType Type)
{
switch (Type) //This is going to be extended
{
case ClassType.GenericMessage:
return BytesToClass<GenericMessage>(Source);
break;
case ClassType.RequestMessage: //RequestMessage is derived from GenericMessage
return BytesToClass<RequestMessage>(Source);
break;
case ClassType.ResponseMessage: //ResponseMessage is derived from GenericMessage
return BytesToClass<ResponseMessage>(Source);
break;
default:
throw new KeyNotFoundException();
break;
}
}
public static T BytesToClass<T>(byte[] Source)
{
int Size = Marshal.SizeOf(typeof(T));
IntPtr Ptr = Marshal.AllocHGlobal(Size);
Marshal.Copy(Source, 0, Ptr, Size);
T result = (T)Marshal.PtrToStructure(Ptr, typeof(T));
Marshal.FreeHGlobal(Ptr);
return result;
}
Essentially what I want to do is:
public static GenericMessage BytesToClass(byte[] Source, ClassType Type)
{
return BytesToClass<Type>(Source);
}
Is there such a way with an enum, or maybe a dictionary?
I've tried and searched, but without any result.
If you want to dynamically supply a generic type, as @usr commented in the comments, you can do it like this:
The
ClassType
enum
members' names has to be exactly the same as the classes' names they represent. Also, this method assumes that the classes you want to convert the byte array into are in theProgram
class (see,typeof(Program)
). Obviously you should change this to make it work with your program.