Created
January 23, 2019 21:47
-
-
Save Porges/e66f90eb9a5781498c11811d7ad28aab to your computer and use it in GitHub Desktop.
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.CompilerServices; | |
using System.Runtime.Serialization; | |
class Program | |
{ | |
static void Main() | |
{ | |
var x = new Person(); | |
Console.WriteLine(x.GetType()); | |
ReallyUnsafeSetType(x, typeof(Dog)); | |
Console.WriteLine(x.GetType()); | |
} | |
unsafe static void ReallyUnsafeSetType(object it, Type t) | |
{ | |
// just need it for its typecode, so don't bother initing | |
var target = FormatterServices.GetUninitializedObject(t); | |
// treating as string lets us pin, it's a magic type | |
// otherwise you can only pin blittable types | |
fixed (char* cIt = Unsafe.As<string>(it)) | |
fixed (char* cTarget = Unsafe.As<string>(target)) | |
{ | |
// copy across typecode (lives 3 ints before first character) | |
*(((int*)cIt) - 3) = *(((int*)cTarget) - 3); | |
} | |
} | |
} | |
class Person { } | |
class Dog { } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment