Add offset to IntPtr

前端 未结 7 1248
庸人自扰
庸人自扰 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条回答
  • 2020-11-30 08:05

    From MSDN: https://docs.microsoft.com/en-us/dotnet/api/system.intptr?view=netcore-3.1

    "The IntPtr type is designed to be an integer whose size is platform-specific. That is, an instance of this type is expected to be 32-bits on 32-bit hardware and operating systems, and 64-bits on 64-bit hardware and operating systems."

            // Summary:
            //     Gets the size of this instance.
            //
            // Returns:
            //     The size of a pointer or handle in this process, measured in bytes. The value
            //     of this property is 4 in a 32-bit process, and 8 in a 64-bit process. You can
            //     define the process type by setting the /platform switch when you compile your
            //     code with the C# and Visual Basic compilers.
            public static int Size { get; }
    

    So if the current code is running in the owning process's context, then the type IntPtr directly inherits the pointer size of the owning process and IntPtr.Size property should return size of pointer in the owning process.

    Since all the above statement are true, we can simply use basic pointer arithmetic

    offset = index*IntPtr.Size

    NOTE: Only thing need to be concerned is to understand process/application target platform and the code which is being used. Ex: Incase your code needs to interact with both x86 and x64 processes acting like a hook then additional safety needs to be adhered else if it was just either one of them, then use plain C style pointer arithmetic

    Again from MSDN:

    static void ReadWriteIntPtr()
    {
        // Allocate unmanaged memory. 
        int elementSize = Marshal.SizeOf(typeof(IntPtr));
        IntPtr unmanagedArray = Marshal.AllocHGlobal(10 * elementSize);
    
        // Set the 10 elements of the C-style unmanagedArray
        for (int i = 0; i < 10; i++)
        {
            Marshal.WriteIntPtr(unmanagedArray, i * elementSize, ((IntPtr)(i + 1)));
        }
        Console.WriteLine("Unmanaged memory written.");
    
        Console.WriteLine("Reading unmanaged memory:");
        // Print the 10 elements of the C-style unmanagedArray
        for (int i = 0; i < 10; i++)
        {
            Console.WriteLine(Marshal.ReadIntPtr(unmanagedArray, i * elementSize));
        }
    
        Marshal.FreeHGlobal(unmanagedArray);
    
        Console.WriteLine("Done. Press Enter to continue.");
        Console.ReadLine();
    }
    
    0 讨论(0)
提交回复
热议问题