c#c++sdk呼び出し時の構造体とbyte配列の相互回転

3454 ワード

/// /// byte /// public static byte[] StructureToByte(T structure) { int size = Marshal.SizeOf(typeof(T)); byte[] buffer = new byte[size]; IntPtr bufferIntPtr = Marshal.AllocHGlobal(size); try { Marshal.StructureToPtr(structure, bufferIntPtr, true); Marshal.Copy(bufferIntPtr, buffer, 0, size); } finally { Marshal.FreeHGlobal(bufferIntPtr); } return buffer; } /// /// byte /// public static T ByteToStructure(byte[] dataBuffer) { object structure = null; int size = Marshal.SizeOf(typeof(T)); IntPtr allocIntPtr = Marshal.AllocHGlobal(size); try { Marshal.Copy(dataBuffer, 0, allocIntPtr, size); structure = Marshal.PtrToStructure(allocIntPtr, typeof(T)); } finally { Marshal.FreeHGlobal(allocIntPtr); } return (T)structure; }
転載する