Created
November 24, 2018 18:57
-
-
Save edgesider/a3c3b775d178487e64cedd80777d2966 to your computer and use it in GitHub Desktop.
C#: interconversion between bytes and struct
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
protected static TStruct BytesToStruct<TStruct>(byte[] bs, int bs_length) where TStruct : new() | |
{ | |
int typeLen = Marshal.SizeOf(typeof(TStruct)); | |
IntPtr tmp = Marshal.AllocHGlobal(typeLen); // 分配托管内存 | |
Marshal.Copy(bs, 0, tmp, bs_length); // 将字节复制到托管内存 | |
TStruct rv = (TStruct)Marshal.PtrToStructure(tmp, typeof(TStruct)); | |
Marshal.FreeHGlobal(tmp); // 释放托管内存 | |
return rv; | |
} | |
protected static bool StructToBytes<TStruct>(TStruct _struct, byte[] buffer) | |
{ | |
int typeLen = Marshal.SizeOf(typeof(TStruct)); | |
if (buffer.Length < typeLen) | |
{ | |
return false; | |
} | |
IntPtr tmp = Marshal.AllocHGlobal(typeLen); | |
Marshal.StructureToPtr(_struct, tmp, false); | |
Marshal.Copy(tmp, buffer, 0, typeLen); | |
Marshal.FreeHGlobal(tmp); | |
return true; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment