Casting a byte array to a managed structure

后端 未结 7 2062
囚心锁ツ
囚心锁ツ 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条回答
  •  Happy的楠姐
    2020-12-02 18:21

    //I have found this at: http://code.cheesydesign.com/?p=572 (I have not tested yet, but // at first sight it will work well.)

        /// 
        /// Reads in a block from a file and converts it to the struct
        /// type specified by the template parameter
        /// 
        /// 
        /// 
        /// 
        private static T FromBinaryReader(BinaryReader reader)
        {
    
            // Read in a byte array
            byte[] bytes = reader.ReadBytes(Marshal.SizeOf(typeof(T)));
    
            // Pin the managed memory while, copy it out the data, then unpin it
            GCHandle handle = GCHandle.Alloc(bytes, GCHandleType.Pinned);
            T theStructure = (T)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(T));
            handle.Free();
    
            return theStructure;
        }
    

提交回复
热议问题