IntPtr.Add(IntPtr, Int32) Method

Definition

为指针值添加偏移量。Adds an offset to the value of a pointer.

public:
 static IntPtr Add(IntPtr pointer, int offset);
public static IntPtr Add (IntPtr pointer, int offset);
static member Add : nativeint * int -> nativeint
Public Shared Function Add (pointer As IntPtr, offset As Integer) As IntPtr

Parameters

pointer
IntPtr

要为其增加偏移量的指针。The pointer to add the offset to.

offset
Int32

要增加的偏移量。The offset to add.

Returns

IntPtr

反映为 offset 增加 pointer 的新指针。A new pointer that reflects the addition of offset to pointer.

Examples

下面的示例实例化一个指向十元素数组开头的 IntPtr 对象,然后调用 Add 方法来循环访问数组中的元素。The following example instantiates an IntPtr object that points to the beginning of a ten-element array, and then calls the Add method to iterate the elements in the array.

using System;
using System.Runtime.InteropServices;

public class Example
{
   public static void Main()
   {
      int[] arr = { 2, 4, 6, 8, 10, 12, 14, 16, 18, 20 };
      unsafe {
         fixed(int* parr = arr) {
            IntPtr ptr = new IntPtr(parr);
            // Get the size of an array element.
            int size = sizeof(int);
            for (int ctr = 0; ctr < arr.Length; ctr++)
            {
               IntPtr newPtr = IntPtr.Add(ptr, ctr * size);
               Console.Write("{0}   ", Marshal.ReadInt32(newPtr));
            }
         }
      }
   }
}
// The example displays the following output:
//       2   4   6   8   10   12   14   16   18   20
Imports System.Runtime.InteropServices

Module Example
   Public Sub Main()
      Dim arr() As Integer = { 2, 4, 6, 8, 10, 12, 14, 16, 18, 20 }
      Dim ptr As IntPtr = Marshal.UnsafeAddrOfPinnedArrayElement(arr, 0)

      For ctr As Integer= 0 To arr.Length - 1
         Dim newPtr As IntPtr = IntPtr.Add(ptr, ctr * Len(arr(0)))
         Console.Write("{0}   ", Marshal.ReadInt32(newPtr))
      Next
   End Sub
End Module
' The example displays the following output:
'       2   4   6   8   10   12   14   16   18   20

Remarks

如果结果太大而无法表示为指定平台上的指针,则 Add 方法不会引发异常。The Add method does not throw an exception if the result is too large to represent as a pointer on the specified platform. 相反,在未检查的上下文中执行加法运算。Instead, the addition operation is performed in an unchecked context.

不支持运算符重载或自定义运算符的语言可以使用此方法将偏移量添加到指针的值。Languages that do not support operator overloading or custom operators can use this method to add an offset to the value of a pointer.

Applies to

See also