Created
February 28, 2013 07:51
-
-
Save TryJSIL/5055026 to your computer and use it in GitHub Desktop.
Simple Unsafe Structs
This file contains hidden or 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
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