Skip to content

Instantly share code, notes, and snippets.

@EgorBo
Created December 13, 2021 21:26
Show Gist options
  • Save EgorBo/6ba5b9d6946a9d05fa961fba01cb1b20 to your computer and use it in GitHub Desktop.
Save EgorBo/6ba5b9d6946a9d05fa961fba01cb1b20 to your computer and use it in GitHub Desktop.
AllocateUninitializedString.cs
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
public class Program
{
static ref byte GetRawData(object obj) =>
ref Unsafe.As<RawData>(obj).Data;
[StructLayout(LayoutKind.Sequential)]
class RawData { public byte Data; }
static ref IntPtr GetMethodTable(object obj) =>
ref Unsafe.Add(ref Unsafe.As<byte, IntPtr>(ref GetRawData(obj)), -1);
static readonly IntPtr StringMT = GetMethodTable("string");
static string AllocateUninitializedString(int length)
{
object obj = GC.AllocateUninitializedArray<char>(length);
GetMethodTable(obj) = StringMT;
return (string)obj;
}
public static void Main(string[] args)
{
string obj = AllocateUninitializedString(100);
Console.WriteLine(obj.GetType());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment