IntPtr.Subtract(IntPtr, Int32) 方法
定义
重要
一些信息与预发行产品相关,相应产品在发行之前可能会进行重大修改。 对于此处提供的信息,Microsoft 不作任何明示或暗示的担保。
从带符号整数中减去偏移量。
public:
static IntPtr Subtract(IntPtr pointer, int offset);
public static IntPtr Subtract (IntPtr pointer, int offset);
static member Subtract : nativeint * int -> nativeint
Public Shared Function Subtract (pointer As IntPtr, offset As Integer) As IntPtr
参数
- pointer
-
IntPtr
nativeint
要从中减去偏移量的带符号整数。
- offset
- Int32
要减去的偏移量。
返回
-
IntPtr
nativeint
一个新的有符号整数,反映从pointer
中减法offset
。
示例
以下示例实例化一个 IntPtr 指向十个元素数组末尾的对象,然后调用 Subtract 该方法以反向顺序循环访问数组中的元素。
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
#nowarn "9"
open System
open System.Runtime.InteropServices
open FSharp.NativeInterop
[<EntryPoint>]
let main _ =
let arr =
[| 2; 4; 6; 8; 10; 12; 14; 16; 18; 20 |]
// Get the size of a single array element.
let size = sizeof<int>
use pend = fixed &arr[arr.GetUpperBound 0]
let ptr = NativePtr.toNativeInt pend
for i = 0 to arr.Length - 1 do
let newPtr = IntPtr.Subtract(ptr, i * size)
printf $"{Marshal.ReadInt32 newPtr} "
0
// The example displays the following output:
// 20 18 16 14 12 10 8 6 4 2
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, arr.Length - 1)
Dim size As Integer = Len(arr(0))
For ctr As Integer = 0 To arr.Length - 1
Dim newPtr As IntPtr = IntPtr.Subtract(ptr, ctr * size)
Console.Write("{0} ", Marshal.ReadInt32(newPtr))
Next
End Sub
End Module
' The example displays the following output:
' 20 18 16 14 12 10 8 6 4 2
注解
如果结果太小而无法表示为执行过程中的有符号整数,则 Subtract 该方法不会引发异常。 相反,减法操作是在未选中的上下文中执行的。
不支持运算符重载或自定义运算符的语言可以使用此方法从指针的值中减去偏移量。