你如何在Python中创建一个IntPtr?

时间:2016-07-09 22:43:54

标签: python .net powershell ctypes intptr

我一直在将PowerShell脚本翻译成python,主要是为了学习如何去做。我在这里遇到了这些问题:

$lpTargetHandle = [IntPtr]::Zero
$CallResult = [Kernel32]::DuplicateHandle(
              $ProcessInfo.hProcess, 0x4,
              [Kernel32]::GetCurrentProcess(),
              [ref]$lpTargetHandle, 0, $false, 0x00000002)

echo $lpTargetHandle

这就是我在python中所拥有的:

lpTargetHandle = HANDLE()
CallResult = kernel32.DuplicateHandle(ProcessInfo.hProcess, 0x4,
             kernel32.GetCurrentProcess(),byref(lpTargetHandle), 0, False, 0x00000002)

print(lpTargetHandle)

以下是我得到的输出:

>>> lpTargetHandle = HANDLE()
>>> CallResult = kernel32.DuplicateHandle(ProcessInfo.hProcess, 0x4, kernel32.GetCurrentProcess(),byref(lpTargetHandle), 0, False, 0x00000002)
>>>
>>> print(lpTargetHandle)
c_void_p(None)
>>> lpTargetHandle.value
>>> type(lpTargetHandle.value)
<type 'NoneType'>

应该发生什么,是lpTargetHandle指针应该返回线程ID号,但我只是得到了Nones。我已经看到IntPtr是在IronPython中处理的,但我的目标是学习vanilla python。我的包括:
from ctypes import * from ctypes.wintypes import *

如何在普通Python(CPython)中复制IntPtr?

具体来说,你如何在python中编写$var = [IntPtr]::Zero

我也尝试了这个,但它不起作用:

tid = POINTER(c_int)
num = c_int(0)
addr = addressof(num)
ptr = cast(addr,tid)
CallResult = = kernel32.DuplicateHandle(ProcessInfo.hProcess, 0x4,
         kernel32.GetCurrentProcess(),ptr, 0, False, 0x00000002)

这是我的完整python code的粘贴盒 这是我正在处理重复的powershell function的pastebin。

编辑:这是我试图在C

中复制的相关功能
 HANDLE hThread = nullptr;  
 DuplicateHandle(procInfo.hProcess, (HANDLE)0x4, 
     GetCurrentProcess(), &hThread, 0, FALSE, DUPLICATE_SAME_ACCESS);
 return hThread;

1 个答案:

答案 0 :(得分:1)

根据Windows documentation,这是函数原型:

BOOL WINAPI DuplicateHandle(
  _In_  HANDLE   hSourceProcessHandle,
  _In_  HANDLE   hSourceHandle,
  _In_  HANDLE   hTargetProcessHandle,
  _Out_ LPHANDLE lpTargetHandle,
  _In_  DWORD    dwDesiredAccess,
  _In_  BOOL     bInheritHandle,
  _In_  DWORD    dwOptions
);

LPHANDLE类型的python中的等价物将是wintypes.LPHANDLE