Skip to content

Instantly share code, notes, and snippets.

@jbevain
Last active December 18, 2024 00:29
Show Gist options
  • Save jbevain/02c8f9823a2b105751dd711673d741b2 to your computer and use it in GitHub Desktop.
Save jbevain/02c8f9823a2b105751dd711673d741b2 to your computer and use it in GitHub Desktop.
using System.Runtime.InteropServices;
unsafe class Program
{
static void Main()
{
ReadOnlySpan<byte> name = stackalloc byte[]
{
(byte)'J',
(byte)'b',
(byte)' ',
(byte)'E',
(byte)'v',
(byte)'a',
(byte)'i',
(byte)'n',
};
Person person = new();
long mem;
fixed (byte*data = &name[0])
{
mem = (long)data;
Console.WriteLine("mem: " + mem);
}
long fna = (long)&person.FirstName;
long lna = (long)&person.LastName;
Console.WriteLine("fna: " + fna);
Console.WriteLine("lna: " + lna);
person.FirstName.offset = (int)(mem - fna);
person.FirstName.length = 2;
person.LastName.offset = (int)(mem + 3 - lna);
person.LastName.length = 5;
PrintHello(ref person);
}
static void PrintHello(ref Person p)
{
var s = p.FirstName.ToString();
var l = p.LastName.ToString();
Console.WriteLine($"Hello {s} {l}!");
}
}
struct Person
{
public BlobString FirstName;
public BlobString LastName;
}
unsafe struct BlobString
{
internal int offset;
internal int length;
public BlobString(int offset, int length)
{
this.offset = offset;
this.length = length;
}
public readonly override string ToString()
{
fixed (int* data = &offset)
{
return Marshal.PtrToStringAnsi((nint)data + offset, length);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment