[英]Whats the difference between open and native handle in c#
I am looking for the difference between我正在寻找两者之间的区别
IntPtr handle_1 = process.Handle;
Gets the native handle of the associated process.
获取关联进程的本机句柄。
[DllImport("kernel32.dll", SetLastError = true)]
public static extern IntPtr OpenProcess(
uint processAccess,
bool bInheritHandle,
uint processId
);
IntPtr handle_2 = OpenProcess(0x0010,false,process.Id);
If the function succeeds, the return value is an open handle to the specified process.
如果 function 成功,则返回值为指定进程的打开句柄。
Both got different values.两者都有不同的价值。 But i can still read the memory with those.
但我仍然可以用这些阅读 memory。 I would like to understand the difference between those two, to prevent making mistakes.
我想了解这两者之间的区别,以防止出错。 I am using them in the context:
我在上下文中使用它们:
ReadProcessMemory(handle_x, addr, data, data.Length, IntPtr.Zero);
Both are process handles, and as such can be used in the same manner.两者都是进程句柄,因此可以以相同的方式使用。
A Process
object contains a process handle through its Handle
property. Process
object 通过其Handle
属性包含进程句柄。 When you call Dispose
on such object, you close that handle.当您在此类 object 上调用
Dispose
时,您将关闭该句柄。
When you call OpenHandle
on the process' ID, you get a different handle (so it has a different value) that refers to the same process.当您在进程的 ID 上调用
OpenHandle
时,您会得到一个引用同一进程的不同句柄(因此它具有不同的值)。 You must separately close that handle when you're done with it (using the Win32 function CloseHandle
): disposing the Process
object won't magically close the handle you got from OpenProcess
.完成后,您必须单独关闭该句柄(使用 Win32 function
CloseHandle
):处理Process
object 不会神奇地关闭您从OpenProcess
获得的句柄。
So why would you call OpenHandle
when you already have a perfectly functional handle in Process
?那么,当您在
Process
中已经有了一个功能完善的句柄时,为什么还要调用OpenHandle
呢? Well, access rights, really.嗯,访问权限,真的。 The handle obtained by
Process
has PROCESS_ALL_ACCESS
(ie full access rights). Process
获得的句柄具有PROCESS_ALL_ACCESS
(即完全访问权限)。 If you want an handle with fewer rights, you can use OpenProcess
for that.如果您想要一个权限较少的句柄,您可以使用
OpenProcess
。
But really, for most purposes, there isn't really a need to mess around with native APIs when you need a process handle.但实际上,在大多数情况下,当您需要进程句柄时,实际上并不需要使用原生 API。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.