Skip to content

Instantly share code, notes, and snippets.

@michel-pi
Last active December 23, 2018 08:50
Show Gist options
  • Save michel-pi/7865eb09fb9bf20112f0fa567b751dfe to your computer and use it in GitHub Desktop.
Save michel-pi/7865eb09fb9bf20112f0fa567b751dfe to your computer and use it in GitHub Desktop.
Extension methods to validate IntPtr's and count with them
using System;
namespace System
{
public static class IntPtrExtensions
{
private static readonly bool _x86 = IntPtr.Size == 4;
public static ulong GetValue(this IntPtr ptr)
{
if(_x86)
{
return (ulong)(uint)ptr;
}
else
{
return (ulong)ptr;
}
}
public static bool IsZero(this IntPtr ptr)
{
return ptr == IntPtr.Zero;
}
public static bool IsNotZero(this IntPtr ptr)
{
return ptr != IntPtr.Zero;
}
public static bool IsValid(this IntPtr ptr)
{
if (_x86)
{
uint value = (uint)ptr;
return (value > 0x10000u && value < 0xFFF00000u);
}
else
{
ulong value = (ulong)ptr;
return (value > 0x10000u && value < 0x000F000000000000u);
}
}
public static IntPtr Add(this IntPtr left, IntPtr right)
{
if (_x86)
{
return new IntPtr((uint)left + (uint)right);
}
else
{
ulong result = (ulong)left + (ulong)right;
return new IntPtr((long)result);
}
}
public static IntPtr Subtract(this IntPtr left, IntPtr right)
{
if (_x86)
{
return new IntPtr((uint)left - (uint)right);
}
else
{
ulong result = (ulong)left - (ulong)right;
return new IntPtr((long)result);
}
}
public static IntPtr Multiply(this IntPtr left, IntPtr right)
{
if (_x86)
{
return new IntPtr((uint)left * (uint)right);
}
else
{
ulong result = (ulong)left * (ulong)right;
return new IntPtr((long)result);
}
}
public static IntPtr Divide(this IntPtr left, IntPtr right)
{
if (_x86)
{
return new IntPtr((uint)left / (uint)right);
}
else
{
ulong result = (ulong)left / (ulong)right;
return new IntPtr((long)result);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment