IntPtr.Zero 필드

정의

0으로 초기화된 서명된 정수 를 나타내는 읽기 전용 필드입니다.

public: static initonly IntPtr Zero;
public static readonly IntPtr Zero;
 staticval mutable Zero : nativeint
Public Shared ReadOnly Zero As IntPtr 

필드 값

IntPtr

nativeint

설명

이 필드의 값은 와 동일 null하지 않습니다. 이 필드를 사용하여 의 IntPtr instance 0이 아닌 값으로 설정되었는지 여부를 효율적으로 확인합니다.

예를 들어 변수 ip가 의 IntPtrinstance 가정합니다. 생성자가 반환한 값(예: " " if ip != new IntPtr(0)... )과 비교하여 설정되었는지 확인할 수 있습니다. 그러나 초기화되지 않은 포인터를 가져오기 위해 생성자를 호출하는 것은 비효율적입니다. " "또는 if !IntPtr.Zero.Equals(ip)... " " if ip != IntPtr.Zero... 를 코딩하는 것이 좋습니다.

관리 코드에서 Windows API를 호출할 때 인수가 포인터 또는 null일 것으로 예상되는 경우 대신 null 를 전달할 IntPtr.Zero 수 있습니다. 예를 들어 Windows CreateFile 함수에 대한 다음 호출은 및 hTemplateFile 인수 값에 pSecurityAttributes 대해 를 제공합니다IntPtr.Zero.

using Microsoft.Win32.SafeHandles;
using System;
using System.Runtime.InteropServices;

public class Example
{
   private const uint GENERIC_READ = 0x80000000;
   private const uint OPEN_EXISTING = 3;
   private const uint FILE_ATTRIBUTE_NORMAL = 128;
   private const uint FILE_FLAG_OVERLAPPED = 0x40000000;

   [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
   private static extern Microsoft.Win32.SafeHandles.SafeFileHandle CreateFile(
            string lpFileName, System.UInt32 dwDesiredAccess, System.UInt32 dwShareMode,
            IntPtr pSecurityAttributes, System.UInt32 dwCreationDisposition,
            System.UInt32 dwFlagsAndAttributes, IntPtr hTemplateFile);

   public static void Main()
   {
      SafeFileHandle hnd = CreateFile("CallOfTheWild.txt", GENERIC_READ, 0,
                                      IntPtr.Zero, OPEN_EXISTING,
                                      FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED,
                                      IntPtr.Zero);
      if (hnd.IsInvalid) {
            Exception ex = Marshal.GetExceptionForHR(Marshal.GetHRForLastWin32Error());
            Console.WriteLine("Attempt to open file failed:");
            Console.WriteLine("  {0}", ex.Message);
            return;
      }
      else {
         Console.WriteLine("File successfully opened.");
         hnd.Close();
      }
   }
}
// If the file cannot be found, the example displays the following output:
//    Attempt to open file failed:
//      The system cannot find the file specified. (Exception from HRESULT: 0x80070002)
open Microsoft.Win32.SafeHandles
open System
open System.Runtime.InteropServices

let GENERIC_READ = 0x80000000u
let OPEN_EXISTING = 3u
let FILE_ATTRIBUTE_NORMAL = 128u
let FILE_FLAG_OVERLAPPED = 0x40000000u

[<DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)>]
extern SafeFileHandle CreateFile(
            string lpFileName, uint dwDesiredAccess, uint dwShareMode,
            nativeint pSecurityAttributes, uint dwCreationDisposition,
            uint dwFlagsAndAttributes, nativeint hTemplateFile)

let hnd = 
    CreateFile("CallOfTheWild.txt", GENERIC_READ, 0u,
               IntPtr.Zero, OPEN_EXISTING,
               FILE_ATTRIBUTE_NORMAL ||| FILE_FLAG_OVERLAPPED,
               IntPtr.Zero)

if hnd.IsInvalid then
    let ex = Marshal.GetExceptionForHR(Marshal.GetHRForLastWin32Error())
    printfn $"Attempt to open file failed:\n  {ex.Message}"
else
    printfn "File successfully opened."
    hnd.Close()

// If the file cannot be found, the example displays the following output:
//    Attempt to open file failed:
//      The system cannot find the file specified. (Exception from HRESULT: 0x80070002)
Imports Microsoft.Win32.SafeHandles
Imports System.Runtime.InteropServices

Module Example
   Private Const GENERIC_READ As UInteger = 2147483648
   Private Const OPEN_EXISTING As UInteger = 3 
   Private Const FILE_ATTRIBUTE_NORMAL As UInteger = 128
   Private Const FILE_FLAG_OVERLAPPED As UInteger = &h40000000

   Private Declare Auto Function CreateFile Lib "Kernel32" Alias "CreateFileW" (
            lpFileName As String, dwDesiredAccess As UInt32, 
            dwShareMode As UInt32, pSecurityAttributes As IntPtr, 
            dwCreationDisposition As UInt32, dwFlagsAndAttributes As UInt32, 
            hTemplateFile As IntPtr) As SafeFileHandle

   Public Sub Main()
      Dim hnd As SafeFileHandle = CreateFile("CallOfTheWild.txt", GENERIC_READ, 0, 
                                             IntPtr.Zero, OPEN_EXISTING,
                                             FILE_ATTRIBUTE_NORMAL Or FILE_FLAG_OVERLAPPED, 
                                             IntPtr.Zero)
      If hnd.IsInvalid Then
         Dim ex As Exception = Marshal.GetExceptionForHR(Marshal.GetHRForLastWin32Error())
         Console.WriteLine("Attempt to open file failed:")
         Console.WriteLine("  {0}", ex.Message)
         Return           
      Else 
         Console.WriteLine("File successfully opened.")
         hnd.Close()     
      End If
   End Sub
End Module
' If the file cannot be found, the example displays the following output:
'    Attempt to open file failed:
'      The system cannot find the file specified. (Exception from HRESULT: 0x80070002)

참고

Zero 포인터 또는 nullZero 일 수 있는 매개 변수 또는 반환 값이 있는 Windows API 함수와 동일 null 하지만 와 동일null하지는 않습니다. 메서드에 전달 null 하면 항상 가 IntPtr.Zero.Equals 반환됩니다 false.

반환된 값을 와 IntPtr.Zero비교하여 포인터 또는 null 를 반환하는 Windows API 함수 호출의 반환 값을 테스트 null 할 수도 있습니다. 예를 들어 다음 예제에서 함수에 대한 호출 GetWindow 은 존재하지 않는 창의 핸들을 검색하려고 시도합니다. 관리되지 않는 코드에서 호출된 경우 함수는 를 반환 null하지만 관리 코드에서 호출되면 를 반환합니다 IntPtr.Zero.

using System;
using System.Runtime.InteropServices;

public class Example
{
   private const int GW_OWNER = 4;

   [DllImport("user32", CharSet=CharSet.Auto, SetLastError=true, ExactSpelling=true)]
   public static extern IntPtr GetWindow(IntPtr hwnd, int wFlag);

   public static void Main()
   {
      IntPtr hwnd = new IntPtr(3);
      IntPtr hOwner = GetWindow(hwnd, GW_OWNER);
      if (hOwner == IntPtr.Zero)
         Console.WriteLine("Window not found.");
   }
}
// The example displays the following output:
//        Window not found.
open System
open System.Runtime.InteropServices

let GW_OWNER = 4

[<DllImport("user32", CharSet=CharSet.Auto, SetLastError=true, ExactSpelling=true)>]
extern IntPtr GetWindow(nativeint hwnd, int wFlag)

let hwnd = IntPtr 3
let hOwner = GetWindow(hwnd, GW_OWNER)
if hOwner = IntPtr.Zero then
    printfn "Window not found."

// The example displays the following output:
//        Window not found.
Module Example
   Private Const GW_OWNER As Integer = 4

   Private Declare Function GetWindow Lib "user32" (hWnd As IntPtr, 
                            wFlag As Integer) As IntPtr 

   Public Sub Main()
      Dim hwnd = new IntPtr(3)
      Dim hOwner As IntPtr = GetWindow(hwnd, GW_OWNER)
      If hOwner = IntPtr.Zero Then
         Console.WriteLine("Window not found.")
      End If   
   End Sub
End Module
' The example displays the following output:
'       Window not found.

적용 대상