Skip to content

Instantly share code, notes, and snippets.

@spixy
Last active May 15, 2019 00:32
Show Gist options
  • Save spixy/63b6e67e303f51e80068193feac48706 to your computer and use it in GitHub Desktop.
Save spixy/63b6e67e303f51e80068193feac48706 to your computer and use it in GitHub Desktop.
public unsafe struct Pointer<T>
{
private void* m_value;
public T Value
{
get => Unsafe.Read<T>(m_value);
set => Unsafe.Write(m_value, value);
}
public T this[int index]
{
get => Unsafe.Read<T>(Offset(m_value, index));
set => Unsafe.Write(Offset(m_value, index), value);
}
public Pointer(ref T t)
{
TypedReference tr = __makeref(t);
IntPtr ptr = *(IntPtr*)(&tr);
m_value = ptr.ToPointer();
}
public Pointer(System.IntPtr p) : this(p.ToPointer())
{
}
public Pointer(void* v)
{
m_value = v;
}
public override string ToString()
{
return Value.ToString();
}
public static implicit operator Pointer<T>(void* v)
{
return new Pointer<T>(v);
}
public static implicit operator Pointer<T>(System.IntPtr p)
{
return new Pointer<T>(p);
}
public static Pointer<T> operator ++(Pointer<T> p)
{
p.Increment(+1);
return p;
}
public static Pointer<T> operator --(Pointer<T> p)
{
p.Increment(-1);
return p;
}
private void Increment(int count)
{
m_value = Offset(m_value, count);
}
private static void* Offset(void* p, int elemCnt)
{
int size = Unsafe.SizeOf<T>();
size *= elemCnt;
return (void*)(((long)p) + size);
}
}
public static void Main(string[] args)
{
int variable = 42;
var ptr = new Pointer<int>(ref variable);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment