Skip to content

Instantly share code, notes, and snippets.

@7shi
Created July 10, 2014 08:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 7shi/981720c2daec6b22b23d to your computer and use it in GitHub Desktop.
Save 7shi/981720c2daec6b22b23d to your computer and use it in GitHub Desktop.
[F#]シリアライズのテスト
#nowarn "9"
open System
open System.IO
open System.Runtime.InteropServices
[<StructLayout(LayoutKind.Sequential)>]
type Test = struct
val mutable Foo:int
val mutable Bar:uint16
val mutable Baz:uint16
end
let showval o =
for f in o.GetType().GetFields() do
let v = f.GetValue(o)
printfn "%s : %s = %A" f.Name (v.GetType().Name) v
let readbin<'a> (bytes:byte[]) =
let gch = GCHandle.Alloc(bytes, GCHandleType.Pinned)
let o = Marshal.PtrToStructure(gch.AddrOfPinnedObject(), typeof<'a>)
gch.Free()
unbox<'a> o
let writebin o =
let size = Marshal.SizeOf(o.GetType())
let bytes = Array.zeroCreate<byte> size
let gch = GCHandle.Alloc(bytes, GCHandleType.Pinned)
Marshal.StructureToPtr(o, gch.AddrOfPinnedObject(), false)
gch.Free()
bytes
let hexstr bytes =
bytes |> Seq.map (sprintf "%02x") |> String.concat " "
let rnd size =
let data = Array.zeroCreate<byte> size
let r = Random()
r.NextBytes data
data
let mutable t = Test(Foo = 5)
t.Bar <- 2us
showval t
printfn "%s" (hexstr(writebin t))
t <- readbin(rnd(Marshal.SizeOf t))
printfn ""
showval t
printfn "%s" (hexstr(writebin t))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment