I have an array of bytes. I built a code generator that will take these array of bytes (which are messages sent from an exchange) into managed structs via the following ReinterpretCast
implementation:
public static T ReinterpretCast<T>(byte[] message) where T : struct
{
GCHandle handle = GCHandle.Alloc(message, GCHandleType.Pinned);
T theStruct = (T)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(T));
handle.Free();
return theStruct;
}
For example ExecutionReportCancel534 item = ReinterpretCast<ExecutionReportCancel534>(myByteArray)
;
As you can see, the last three digits of this type is 534. 534 is the ID that corresponds to this type. My code generator creates a dictionary that maps these IDs to types. For instance,
public const Dictionary<int, Type> intToStructMap = new Dictionary<int, Type>()
{
{ 500, Negotiate500 },
{ 501, NegotiationResponse501 },
{ 502, NegotiationReject502 },
{ 503, Establish503 },
{ 504, EstablishmentAck504 },
{ 505, EstablishmentReject505 },
};
Now, what I want to do is write a function that takes: 1) an array of bytes, and 2) an integer, and return a type that is reinterpreted from this array of bytes. For example, while I know this is not possible, I'd like this function to operate like this:
public static intToStructMap[templateId] ReinterpretCast(byte[] message, int templateId)
{
Type typeOfInterest = intToStructMap[templateId];
var returnedStruct = ReinterpretCast<typeOfInterest>(message);
return returnedStruct;
}
In other words, I want to return any of the types in my dictionary (intToStructMap
) given the templateId that corresponds to this type.
Whats the best way to do so?
Aucun commentaire:
Enregistrer un commentaire