Add offset to IntPtr
Solution 1:
In .net 4 static Add() and Subtract() methods have been added.
IntPtr ptr = IntPtr.Add(oldPtr, 2);
http://msdn.microsoft.com/en-us/library/system.intptr.add.aspx
Solution 2:
I suggest you to use ToInt64() and long to perform your computation. This way you will avoid problem on 64 bits version of the .NET framework.
IntPtr ptr = new IntPtr(oldptr.ToInt64() + 2);
This add a bit of overhead on 32 bits system, but it is safer.
Solution 3:
For pointer arithmetic in C# you should use proper pointers inside an unsafe
context:
class PointerArithmetic
{
unsafe static void Main()
{
int* memory = stackalloc int[30];
long* difference;
int* p1 = &memory[4];
int* p2 = &memory[10];
difference = (long*)(p2 - p1);
System.Console.WriteLine("The difference is: {0}", (long)difference);
}
}
The IntPtr
type is for passing around handles or pointers and also for marshalling to languages that support pointers. But it's not for pointer arithmetic.