Created
July 10, 2014 08:57
-
-
Save 7shi/981720c2daec6b22b23d to your computer and use it in GitHub Desktop.
[F#]シリアライズのテスト
This file contains 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
#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