Skip to content

Instantly share code, notes, and snippets.

@kos59125
Created November 26, 2012 02:24
Show Gist options
  • Select an option

  • Save kos59125/4146255 to your computer and use it in GitHub Desktop.

Select an option

Save kos59125/4146255 to your computer and use it in GitHub Desktop.
Tried to make a type of C union, but failed
open System
open System.Runtime.InteropServices
(* C code
union S {
uint32_t u32[4];
uint64_t u64[2];
};
*)
[<Struct>]
[<StructLayout(LayoutKind.Explicit)>]
type S =
[<MarshalAs(UnmanagedType.ByValArray, SizeConst = 4, ArraySubType = UnmanagedType.U4)>]
[<FieldOffset(0)>]
val u32 : uint32 []
[<MarshalAs(UnmanagedType.ByValArray, SizeConst = 2, ArraySubType = UnmanagedType.U8)>]
[<FieldOffset(0)>]
val u64 : uint64 []
[<EntryPoint>]
let main args =
let ptr = Marshal.AllocHGlobal (Marshal.SizeOf (typeof<S>))
try
Marshal.Copy ([| 1L; 2L |], 0, ptr, 2)
let s = Marshal.PtrToStructure (ptr, typeof<S>) :?> S
printfn "%A" s.u32 // expected [|1u; 0u; 2u; 0u|], actual [|1UL; 2UL|]
printfn "%A" s.u64 // expected [|1UL; 2UL|], actual [|1UL; 2UL|]
finally
Marshal.FreeHGlobal (ptr)
0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment