如何转换的IntPtr为int [英] How to convert IntPtr to int

查看:335
本文介绍了如何转换的IntPtr为int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个窗口有时手柄式 INT 和类型的其他时间的IntPtr

A window handle sometimes of type int and other times of type IntPtr

INT 例如:

 [DllImport("user32.dll")]
    static extern uint GetWindowThreadProcessId(int hWnd, int ProcessId);    



的IntPtr 例如:

  [DllImport("user32.dll", CharSet = CharSet.Auto)]
    static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, int wParam, StringBuilder lParam);



我似乎不能够从一个到另一个转换/施放。

I don't seem to be able to convert/cast from one to the other.

当我尝试 this.ProcessID = GetWindowThreadProcessId(windowHandle.ToInt32(),0)我得到一个错误不能隐式地从UINT转换为int

When I try this.ProcessID = GetWindowThreadProcessId(windowHandle.ToInt32(),0) I get an error cannot implicitly convert from uint to int

推荐答案

SendMessage函数签名

static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam);

或本

static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, StringBuilder lParam);



不交换 INT 的IntPtr 。它们仅在32位(大小相等)几乎相等。在64位的的IntPtr 几乎相当于一个(大小相等)

Don't exchange int and IntPtr. They are nearly equivalent only at 32 bits (equal in size). At 64 bits an IntPtr is nearly equivalent to a long (equal in size)

GetWindowThreadProcessId 签名

static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);

static extern uint GetWindowThreadProcessId(IntPtr hWnd, IntPtr ProcessId);

在这种情况下, REF 退出来东西进行管理的东西引用,所以传递给本机API时,他们内部转换为的IntPtr 。因此,出UINT 是,从本机API,相当于的IntPtr

In this case, a ref or a out to "something" are managed references to something, so they are internally converted to IntPtr when passed to Native API. So out uint is, from the point of view of the Native API, equivalent to IntPtr.

说明:最重要的是,该参数的长度是正确的。 INT UINT 相等时,称为API。和一个32位的的IntPtr 太一样的。

Explanation: what is important is that the "length" of the parameters is the correct one. int and uint are equal for the called API. And a 32bit IntPtr is the same too.

请注意,某些类型(如布尔字符)具有由封送特殊处理。

Note that some types (like bool and char) have special handling by the marshaler.

您不应该EVER转换一个 INT 的IntPtr 。把它作为一个的IntPtr 和生活幸福。如果你必须做出不受的IntPtr 支持一些数学运算,使用(这是64位,所以直到我们将拥有的窗口128 的,不会有任何问题:-))。

You shouldn't EVER convert an int to an IntPtr. Keep it as an IntPtr and live happy. If you have to make some math operations not supported by IntPtr, use long (it's 64 bits, so until we will have Windows 128, there won't be any problem :-) ).

IntPtr p = ...
long l = (long)p;
p = (IntPtr)l;

这篇关于如何转换的IntPtr为int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆