Skip to content

Instantly share code, notes, and snippets.

@main--
Created February 13, 2015 14:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save main--/6d32ad57f7dbec058431 to your computer and use it in GitHub Desktop.
Save main--/6d32ad57f7dbec058431 to your computer and use it in GitHub Desktop.
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