GetWindowLong vs GetWindowLongPtr in C#

余生长醉 提交于 2019-12-10 20:25:44

问题


I was using GetWindowLong like this:

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

But according to the MSDN docs I am supposed to be using GetWindowLongPtr to be 64bit compatible. http://msdn.microsoft.com/en-us/library/ms633584(VS.85).aspx

The MSDN docs for GetWindowLongPtr say that I should define it like this (in C++):

LONG_PTR GetWindowLongPtr(HWND hWnd, int nIndex);

I used to be using IntPtr as the return type, but what the heck would I use for an equivalent for LONG_PTR? I have also seen GetWindowLong defined as this in C#:

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

What is right, and how can I ensure proper 64bit compatibility?


回答1:


Unfortunately it's not that easy, because GetWindowLongPtr doesn't exist in 32bit Windows. On 32bit systems GetWindowLongPtr is just a C macro that points to GetWindowLong. If you really need to use GetWindowLongPtr on both 32 and 64 bit systems you'll have to determine the correct one to call at run time. See the description at pinvoke.net




回答2:


You should define GetWindowLongPtr using an IntPtr. In C/C++ a LONG_PTR is 32-bits on a 32-bit system and 64-bits on a 64-bit system (see here). IntPtr in C# is designed to work the same way (see here).

So what you want is:

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



回答3:


SoapBox is correct.

Additionally, if you ever need to see how a type or function should Marshal in Win32, try using the PInvoke Interop Assistant. It will has built-in generations for most Win32 API's and can do custom generation based off of code snippets.



来源:https://stackoverflow.com/questions/319672/getwindowlong-vs-getwindowlongptr-in-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!