Casting a byte array to a managed structure

后端 未结 7 2057
囚心锁ツ
囚心锁ツ 2020-12-02 17:48

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

相关标签:
7条回答
  • 2020-12-02 18:30

    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.

    0 讨论(0)
提交回复
热议问题