如何在C#.Net中将空指针传递给Win32 API?

Tho*_*ith 9 c# null pinvoke

我正在查看RegisterHotKey函数:

http://msdn.microsoft.com/en-us/library/ms646309(VS.85).aspx

BOOL RegisterHotKey(
  __in  HWND hWnd,
  __in  int id,
  __in  UINT fsModifiers,
  __in  UINT vk
);
Run Code Online (Sandbox Code Playgroud)

我一直在使用IntPtr传递第一个参数,在大多数情况下都能正常工作.但是现在我需要故意传递一个空指针作为第一个参数,IntPtr(故意)不会这样做.我是.Net的新手,这让我感到困惑.我怎样才能做到这一点?

Jar*_*Par 18

使用IntPtr.ZeroNULL

例如:

public void Example() {
  ...
  RegisterHotKey(IntPtr.Zero, id, mod, vk);
}

[DllImportAttribute("user32.dll", EntryPoint="RegisterHotKey")]
[return: MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.Bool)]
public static extern bool RegisterHotKey(
  IntPtr hWnd, 
  int id, 
  uint fsModifiers, 
  uint vk);
Run Code Online (Sandbox Code Playgroud)

  • @Thom,`IntPtr.Zero`是一个地址为0的指针.它实际上指向什么,因为取消引用地址0几乎肯定会导致崩溃或排序异常.C++值NULL具有相同的行为(地址为0的指针)因此它与`IntPtr.Zero很好地匹配 (4认同)