2008-11-26 69 views
2

我使用GetWindowLong這樣的:GetWindowLong VS GetWindowLongPtr在C#

[DllImport("user32.dll")] 
private static extern IntPtr GetWindowLong(IntPtr hWnd, int nIndex); 

但根據MSDN文檔我應該使用GetWindowLongPtr將64位兼容。 http://msdn.microsoft.com/en-us/library/ms633584(VS.85).aspx

MSDN文檔爲GetWindowLongPtr說,我應該把它定義像這樣(用C++):

LONG_PTR GetWindowLongPtr(HWND hWnd, int nIndex); 

我以前使用的IntPtr返回類型,但赫克我會用什麼LONG_PTR的等價物?我也看到GetWindowLong在C#中將其定義爲:

[DllImport("user32.dll")] 
private static extern long GetWindowLong(IntPtr hWnd, int nIndex); 

什麼是正確的,以及如何確保正確的64位兼容性?

+0

這兩個DllImport語句都不正確:在64位Windows上,GetWindowLong不返回IntPtr,並且在32位Windows上,GetWindowLong不返回長整型。 – 2008-11-26 03:45:08

回答

6

不幸的是,這並不容易,因爲GetWindowLongPtr在32位Windows中不存在。在32位系統上,GetWindowLongPtr只是一個指向GetWindowLong的C宏。如果您確實需要在32位和64位系統上使用GetWindowLongPtr,則必須在運行時確定要調用的正確調用。請參閱pinvoke.net的描述

7

您應該使用IntPtr定義GetWindowLongPtr。在C/C++中,LONG_PTR是32位系統上的32位和64位系統上的64位(請參閱here)。 C#中的IntPtr被設計爲以相同的方式工作(請參閱here)。

所以,你想要的是:

[DllImport("user32.dll")] 
private static extern IntPtr GetWindowLongPtr(IntPtr hWnd, int nIndex); 
3

肥皂盒是正確的。

此外,如果您需要在Win32中查看類型或函數應該如何變成Marshal,請嘗試使用PInvoke Interop Assistant。它將爲大多數Win32 API提供內置的代碼,並且可以基於代碼片段進行自定義生成。

+0

感謝您的優秀鏈接 - 我想我只是找到了一個新的最喜歡的工具。 – 2008-11-26 05:22:58