Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add offset to IntPtr

I'm looking for a way to perform pointer operations in C# or .NET in particular.

I want to do something very simple

Having a pointer IntPtr I want to get IntPtr object which points to 2 bytes ahead.

I read some post that the foolowing snippet will work...

IntPtr ptr = new IntPtr(oldptr.ToInt32() + 2);

But I have doubts whether this statement is also valid for 64-bit machine (since addressing is in 64-bits there)..

I found this elegant method to add offset, but unfortunately is in .NET 4.0 only http://msdn.microsoft.com/en-us/library/system.intptr.add%28VS.100%29.aspx

like image 338
Marcin Rybacki Avatar asked Dec 08 '09 11:12

Marcin Rybacki


4 Answers

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.

like image 42
Laurent Etiemble Avatar answered Nov 08 '22 02:11

Laurent Etiemble


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

like image 139
BLeB Avatar answered Nov 08 '22 04:11

BLeB


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.

like image 9
Joey Avatar answered Nov 08 '22 04:11

Joey


I found that I can avoid pointer operations by using Marshal.ReadByte(), Marshal.ReadInt16() etc. methods. This group of methods allow to specify offset in releation to the IntPtr...

like image 9
Marcin Rybacki Avatar answered Nov 08 '22 03:11

Marcin Rybacki