構造体をStreamに書き込む

ビットマップファイルを作ったりするときに必要ですが、ちょっと面倒です。

構造体サイズ分のアンマネージメモリを確保し、そこに構造体をコピー。
さらにそこからbyte[]へコピーしてStreamに書き込んでいます。

public static void WriteStructToStream(System.IO.Stream s, object obj) {
    int len = System.Runtime.InteropServices.Marshal.SizeOf(obj);
    IntPtr pBuff = System.Runtime.InteropServices.Marshal.AllocHGlobal(len);
    System.Runtime.InteropServices.Marshal.StructureToPtr(obj, pBuff, false);
    byte[] buff = new byte[len];
    System.Runtime.InteropServices.Marshal.Copy(pBuff, buff, 0, buff.Length);
    System.Runtime.InteropServices.Marshal.FreeHGlobal(pBuff);
    s.Write(buff, 0, buff.Length);
}

名前空間全部書いてるので無駄に長いですが、こんな感じでできます。