英語で読む

次の方法で共有


IntPtr.Subtract(IntPtr, Int32) メソッド

定義

符号付き整数からオフセットを減算します。

C#
public static IntPtr Subtract (IntPtr pointer, int offset);

パラメーター

pointer
IntPtr

オフセットを減算する符号付き整数。

offset
Int32

減算するオフセット。

戻り値

IntPtr

from pointerの減算offsetを反映する新しい符号付き整数。

次の例では、10 要素配列の末尾を指すオブジェクトをインスタンス化 IntPtr し、メソッドを Subtract 呼び出して配列内の要素を逆の順序で反復処理します。

C#
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};
      // Get the size of a single array element.
      int size = sizeof(int);
      unsafe {
         fixed(int* pend = &arr[arr.GetUpperBound(0)]) {
            IntPtr ptr = new IntPtr(pend);
            for (int ctr = 0; ctr < arr.Length; ctr++)
            {
               IntPtr newPtr = IntPtr.Subtract(ptr, ctr * size);
               Console.Write("{0}   ", Marshal.ReadInt32(newPtr));
            }
         }
      }
   }
}
// The example displays the following output:
//       20   18   16   14   12   10   8   6   4   2

注釈

結果が小さすぎて実行中のプロセスで符号付き整数として表現できない場合、メソッドは Subtract 例外をスローしません。 代わりに、減算操作はオフのコンテキストで実行されます。

演算子のオーバーロードやカスタム演算子をサポートしていない言語では、このメソッドを使用してポインターの値からオフセットを減算できます。

適用対象

製品 バージョン
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7
.NET Framework 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

こちらもご覧ください