Skip to content

Instantly share code, notes, and snippets.

@Shadowblitz16
Created July 22, 2022 20:35
Show Gist options
  • Save Shadowblitz16/da7debbf4746ad00e7bff08e9dbb3118 to your computer and use it in GitHub Desktop.
Save Shadowblitz16/da7debbf4746ad00e7bff08e9dbb3118 to your computer and use it in GitHub Desktop.
Generic IntPtr struct for C#
public readonly struct IntPtr<T> where T : unmanaged
{
private readonly IntPtr _data;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe IntPtr(IntPtr value)
{
unsafe
{
_data = value;
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe IntPtr(T* value)
{
unsafe
{
_data = new IntPtr(value);
var a = IntPtr.MaxValue;
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe implicit operator T*(IntPtr<T> ptr)
{
return (T*)ptr._data.ToPointer();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe implicit operator IntPtr<T>(T* ptr)
{
return new IntPtr<T>(ptr);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static implicit operator IntPtr(IntPtr<T> ptr)
{
return ptr._data;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static implicit operator IntPtr<T>(IntPtr ptr)
{
return new IntPtr<T>(ptr);
}
public static int Size
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => IntPtr.Size;
}
public static IntPtr<T> Zero
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => IntPtr.Zero;
}
public static IntPtr<T> MaxValue
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => IntPtr.MaxValue;
}
public static IntPtr<T> MinValue
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => IntPtr.MinValue;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment