Created
February 13, 2015 14:22
-
-
Save main--/6d32ad57f7dbec058431 to your computer and use it in GitHub Desktop.
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
using System; | |
using System.Runtime.InteropServices; | |
using System.Text; | |
namespace Unsafe | |
{ | |
[StructLayout(LayoutKind.Explicit)] | |
public struct Union | |
{ | |
[FieldOffset(0)] | |
public long Long; | |
[FieldOffset(0)] | |
public string String; | |
} | |
class MainClass | |
{ | |
public static void Main(string[] args) | |
{ | |
var text = "Go home, you're drunk!"; | |
var thing = new byte[1024]; | |
thing[16] = checked((byte)text.Length); // length prefix (255 char max due to my laziness) | |
Encoding.Unicode.GetBytes(text, 0, text.Length, thing, 20); // the actual string | |
var handle = GCHandle.Alloc(thing, GCHandleType.Pinned); | |
var mu = new Union(); | |
mu.Long = handle.AddrOfPinnedObject().ToInt64(); | |
Console.WriteLine(mu.String.Length); | |
Console.WriteLine(mu.String); | |
// let's have some fun, just for good measures | |
thing[16] = thing[17] = thing[18] = thing[19] = 0xFF; | |
Console.WriteLine(mu.String.Length); | |
handle.Free(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment