LoginSignup
20
19

More than 5 years have passed since last update.

C#でstructをバイト配列に変換する拡張メソッド

Posted at

public static byte[] ToByteArray<T>(this T structure) where T : struct
{
    byte[] bb = new byte[Marshal.SizeOf(typeof(T))];
    GCHandle gch = GCHandle.Alloc(bb, GCHandleType.Pinned);
    Marshal.StructureToPtr(structure, gch.AddrOfPinnedObject(), false);
    gch.Free();
    return bb;
}

よく使うネタです。

20
19
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
20
19