Created
December 8, 2022 04:43
-
-
Save qt-kaneko/cc8e956326e113966b09c522d0efec49 to your computer and use it in GitHub Desktop.
C# in stack object allocation
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.Runtime.CompilerServices; | |
using System.Runtime.InteropServices; | |
unsafe | |
{ | |
var type = typeof(Test); | |
var typeHandle = type.TypeHandle.Value; | |
var size = Marshal.ReadInt32(typeHandle, 4); | |
var memory = stackalloc byte[size]; | |
var pointer = new IntPtr(memory) + 4; | |
Marshal.WriteIntPtr(pointer, typeHandle); | |
var instance = Unsafe.As<IntPtr, Test>(ref pointer); | |
type.GetConstructor(new Type[0])!.Invoke(instance, new object[0]); | |
Console.WriteLine(instance.A); // Should be 80085 | |
} | |
class Test | |
{ | |
public int A = 80085; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment