Last active
December 23, 2018 08:50
-
-
Save michel-pi/7865eb09fb9bf20112f0fa567b751dfe to your computer and use it in GitHub Desktop.
Extension methods to validate IntPtr's and count with them
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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