Update: Answers to this question helped me code the open sourced project AlicanC\'s Modern Warfare 2 Tool on GitHub. You can see how I am reading these packets in MW
For those who have access to C# 7.3 features, I use this piece of unsafe code to "serialize" to bytes:
public static class Serializer
{
public static unsafe byte[] Serialize<T>(T value) where T : unmanaged
{
byte[] buffer = new byte[sizeof(T)];
fixed (byte* bufferPtr = buffer)
{
Buffer.MemoryCopy(&value, bufferPtr, sizeof(T), sizeof(T));
}
return buffer;
}
public static unsafe T Deserialize<T>(byte[] buffer) where T : unmanaged
{
T result = new T();
fixed (byte* bufferPtr = buffer)
{
Buffer.MemoryCopy(bufferPtr, &result, sizeof(T), sizeof(T));
}
return result;
}
}
A unmanaged
type can be a struct (simple struct without reference types, those a considered managed structs) or a native type such as int
, short
, etc.