直接上代碼:
1、
my_debugger_defines.py
定義相關結構體(在后面創建進程及返回信息時,傳參可用到)

1 from ctypes import * 2 # Let's map the Microsoft types to ctypes for clarity 3 Word=c_ushort 4 DWORD=c_ulong 5 LPBYTE=POINTER(c_ubyte) 6 LPTSTR=POINTER(c_char) 7 HANDLE=c_void_p 8 #constants 9 DEBUG_PROCESS=0x0000000110 CREATE_NEW_CONSOLE = 0x0000001011 # Structures for CreateProcessA() function12 class STARTUPINFO(Structure):13 _fields_=[14 ("cb",DWORD),15 ("lpReserved",LPTSTR),16 ("lpDesktop",LPTSTR),17 ("lpTitle",LPTSTR),18 ("dwX",DWORD),19 ("dwY",DWORD),20 ("dwXSize",DWORD),21 ("dwYSize",DWORD),22 ("dwXCountChars",DWORD),23 ("dwYCountChars",DWORD),24 ("dwFlags",DWORD),25 ("wShowWindow",WORD),26 ("bcReserved2",WORD),27 ("lpReserved2",LPBYTE),28 ("hStdInput", HANDLE),29 ("hStdOutput", HANDLE),30 ("hStdError", HANDLE),31 ]32 33 class PROCESS_INFORMATION(Structure):34 _fields_=[35 ("hProcess",HANDLE),36 ("hThread", HANDLE),37 ("dwProcessId", DWORD),38 ("dwThreadId", DWORD),39 ]
2、my_debugger.py
定義創建并跟蹤進程的函數:

1 from ctypes import * 2 from my_debugger_defines import * 3 4 kernel32=windll.kernel32 5 6 class debugger(): 7 def _init_(self): 8 pass 9 def load(self,path_to_exe):10 # dwCreation flag determines how to create the process11 # set creation_flags = CREATE_NEW_CONSOLE if you want12 # to see the calculator GUI13 creation_flags = DEBUG_PROCESS14 15 startupinfo=STARTUPINFO()16 process_information=PROCESS_INFORMATION()17 18 startupinfo.dwFlags=0x119 startupinfo.wShowWindow20 startupinfo.cb=sizeof(startupinfo)21 22 #win32api函數CreatProcess用來創建一個新的進程和他的主線程,23 #這個新進程運行指定的可執行文件,由第一個參數指定24 if kernel32.CreateProcessW(path_to_exe, #should be CreateProcessW ,not CreateProcessA ,it is UNICODE API25 None, 26 None,27 None,28 None,29 #指定附加的、用來控制優先類和進程的創建的標志。30 creation_flags,31 None,32 None,33 #該參數指向一個用于決定新進程的主窗體如何顯示的STARTUPINFO結構體。 34 byref(startupinfo), #byref() 按地址傳遞35 #該參數指向一個用來接收新進程的識別信息的PROCESS_INFORMATION結構體。36 byref(process_information)#這里有個問題:37 #結構體之間的賦值是如何進行的?38 #因為這里定義的process_information跟39 #creatprocess中process_information的參數數量一致40 #而startupinfo是不一致的41 ):42 print("We have sucessfully lunched the process")43 print("PID:%d"%process_information.dwProcessId)44 45 else:46 print("Error:0x%08x."%kernel32.GetLastError())47
嘗試,調用函數:

1 import my_debugger2 3 debugger=my_debugger.debugger()4 5 debugger.load("C:/Windows/System32/calc.exe")
問題:
#結構體之間的賦值是如何進行的?按順序?
#這里自己定義的process_information結構體跟
#win32函數中creatprocess中process_information的成員數量、位置是必須一致的嗎?
#好像也不是這樣,因為我process_information是一致的,成功傳參了,而我startupinfo不一致,也成功了。
關于win32函數中creatprocess中process_information、startupinfo見http://baike.baidu.com/view/2421585.htm
新聞熱點
疑難解答