Skip to content

Instantly share code, notes, and snippets.

@qt-kaneko
Created December 8, 2022 04:43
Show Gist options
  • Save qt-kaneko/cc8e956326e113966b09c522d0efec49 to your computer and use it in GitHub Desktop.
Save qt-kaneko/cc8e956326e113966b09c522d0efec49 to your computer and use it in GitHub Desktop.
C# in stack object allocation
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