Skip to content

Instantly share code, notes, and snippets.

@nikhilm
Forked from TryJSIL/tryjsil.cs
Created April 11, 2013 21:20
Show Gist options
  • Save nikhilm/5367274 to your computer and use it in GitHub Desktop.
Save nikhilm/5367274 to your computer and use it in GitHub Desktop.
Simple Unsafe Structs
using System;
using System.Runtime.InteropServices;
public static class Program {
public static unsafe void Main (string[] args) {
var bytes = new byte[8];
fixed (byte* pBytes = bytes) {
var pStruct = (MyStruct*)pBytes;
*pStruct = new MyStruct {
Int = 2,
Float = 3.5f
};
for (var i = 0; i < bytes.Length; i++)
Console.Write("{0:X2} ", bytes[i]);
Console.WriteLine();
bytes[0] += 1;
bytes[1] += 2;
bytes[6] += 1;
Console.WriteLine(*pStruct);
}
}
}
public struct MyStruct {
public int Int;
public float Float;
public override string ToString () {
return String.Format("Int={0:0000}, Float={1:000.000}", Int, Float);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment