Add offset to IntPtr

前端 未结 7 1300
庸人自扰
庸人自扰 2020-11-30 06:59

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 I

7条回答
  •  猫巷女王i
    2020-11-30 07:55

    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.

提交回复
热议问题