Skip to content

Instantly share code, notes, and snippets.

@joncham
Created February 28, 2023 19:21
Show Gist options
  • Save joncham/a049654da992a5e0e22c94022a958e2a to your computer and use it in GitHub Desktop.
Save joncham/a049654da992a5e0e22c94022a958e2a to your computer and use it in GitHub Desktop.
Writing Value to Managed Object at an Offset
using System.Runtime.CompilerServices;
class Program
{
static void Main(string[] args)
{
TestSetIntAtOffset();
}
public static void TestSetIntAtOffset()
{
var boxedInt = (object)10;
var offset = 8;
SetIntAtOffset(boxedInt, 8, 20);
Console.WriteLine(boxedInt);
}
public unsafe static void SetIntAtOffset(object o, int offset, int value)
{
const int kObjectHeader = 8;
fixed (byte* data = new ObjectPinner(o))
{
var target = data + offset - kObjectHeader;
int oldValue = Unsafe.AsRef<int>(target);
Unsafe.AsRef<int>(target) = value;
Console.WriteLine(oldValue);
}
}
unsafe struct ObjectPinner
{
public ObjectPinner(object o)
{
this.o = o;
}
public ref byte GetPinnableReference()
{
return ref Unsafe.As<ObjectWrapper>(o).GetPinnableReference();
}
class ObjectWrapper
{
public byte Data;
public ref byte GetPinnableReference() => ref Data;
}
object o;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment