在python中某些時候需要C做效率上的補充,在實際應用中,需要做部分數據的交互。使用python中的ctypes模塊可以很方便的調用windows的dll(也包括linux下的so等文件),下面將詳細的講解這個模塊(以windows平台為例子),當然我假設你們已經對windows下怎么寫一個DLL是沒有問題的。
引入ctypes庫
- from ctypes import *
假設你已經有了一個的DLL(名字是add.dll),且該DLL有一個符合cdecl(這里強調調用約定是因為,stdcall調用約定和cdecl調用約定聲明的導出函數,在使用python加載時使用的加載函數是不同的,后面會有說明)調用約定的導出函數Add。
建立一個Python文件DllCall.py測試:
- from ctypes import *
- dll = CDLL("add.dll")
- print dll.Add(1, 102)
結果:103
上面是一個簡單的例子。下面簡單聊一下調用流程:
1、加載DLL
上面已經說過,加載的時候要根據你將要調用的函數是符合什么調用約定的。
stdcall調用約定:兩種加載方式
- Objdll = ctypes.windll.LoadLibrary("dllpath")
- Objdll = ctypes.WinDLL("dllpath")
cdecl調用約定:也有兩種加載方式
- Objdll = ctypes.cdll.LoadLibrary("dllpath")
- Objdll = ctypes.CDLL("dllpath")
- /*其實windll和cdll分別是WinDLL類和CDll類的對象。*/
2、調用dll中的方法
在1中加載dll的時候會返回一個DLL對象(假設名字叫Objdll),利用該對象就可以調用dll中的方法。
e.g.如果dll中有個方法名字叫Add(注意如果經過stdcall聲明的方法,如果不是用def文件聲明的導出函數或者extern “C” 聲明的話,編譯器會對函數名進行修改,這個要注意,我想你們懂的。)
調用:nRet = Objdll.Add(12, 15) 即完成一次調用。
看起來調用似乎很簡單,不要只看表象,呵呵,這是因為Add這個函數太簡單了,現在假設函數需要你傳入一個int類型的指針(int*),可以通過庫中的byref關鍵字來實現,假設現在調用的函數的第三個參數是個int類型的指針。
- intPara = c_int(9)
- dll.sub(23, 102, byref(intPara))
- print intPara.value
如果是要傳入一個char緩沖區指針,和緩沖區長度,方法至少有四種:
- # 方法1
- szPara = create_string_buffer('/0'*100)
- dll.PrintInfo(byref(szPara), 100);
- print szPara.value
- # 方法2
- sBuf = 'aaaaaaaaaabbbbbbbbbbbbbb'
- pStr = c_char_p( )
- pStr.value = sBuf
- #pVoid = ctypes.cast( pStr, ctypes.c_void_p ).value
- dll.PrintInfo(pStr, len(pStr.value))
- print pStr.value
- # 方法3
- strMa = "/0"*20
- FunPrint = dll.PrintInfo
- FunPrint.argtypes = [c_char_p, c_int]
- #FunPrint.restypes = c_void_p
- nRst = FunPrint(strMa, len(strMa))
- print strMa,len(strMa)
- # 方法4
- pStr2 = c_char_p("/0")
- print pStr2.value
- #pVoid = ctypes.cast( pStr, ctypes.c_void_p ).value
- dll.PrintInfo(pStr2, len(pStr.value))
- print pStr2.value
3、C基本類型和ctypes中實現的類型映射表
ctypes數據類型 C數據類型
c_char char
c_short short
c_int int
c_long long
c_ulong unsign long
c_float float
c_double double
c_void_p void
對應的指針類型是在后面加上"_p",如int*是c_int_p等等。
在python中要實現c語言中的結構,需要用到類。
4、DLL中的函數返回一個指針。
雖然這不是個好的編程方法,不過這種情況的處理方法也很簡單,其實返回的都是地址,把他們轉換相應的python類型,再通過value屬性訪問。
- pchar = dll.getbuffer()
- szbuffer = c_char_p(pchar)
- print szbuffer.value
5、處理C中的結構體類型
為什么把這個單獨提出來說呢,因為這個是最麻煩也是最復雜的,在python里面申明一個類似c的結構體,要用到類,並且這個類必須繼承自Structure。
先看一個簡單的例子:
C里面dll的定義如下:
- typedef struct _SimpleStruct
- {
- int nNo;
- float fVirus;
- char szBuffer[512];
- } SimpleStruct, *PSimpleStruct;
- typedef const SimpleStruct* PCSimpleStruct;
- extern "C"int __declspec(dllexport) PrintStruct(PSimpleStruct simp);
- int PrintStruct(PSimpleStruct simp)
- {
- printf ("nMaxNum=%f, szContent=%s", simp->fVirus, simp->szBuffer);
- return simp->nNo;
- }
Python的定義:
- from ctypes import *
- class SimpStruct(Structure):
- _fields_ = [ ("nNo", c_int),
- ("fVirus", c_float),
- ("szBuffer", c_char * 512)]
- dll = CDLL("AddDll.dll")
- simple = SimpStruct();
- simple.nNo = 16
- simple.fVirus = 3.1415926
- simple.szBuffer = "magicTong/0"
- print dll.PrintStruct(byref(simple))
上面例子結構體很簡單,但是如果結構體里面有指針,甚至是指向結構體的指針,處理起來會復雜很多,不過Python里面也有相應的處理方法,下面這個例子來自網上,本來想自己寫個,懶得寫了,能說明問題就行:
C代碼如下:
- typedef struct
- {
- char words[10];
- }keywords;
- typedef struct
- {
- keywords *kws;
- unsigned int len;
- }outStruct;
- extern "C"int __declspec(dllexport) test(outStruct *o);
- int test(outStruct *o)
- {
- unsigned int i = 4;
- o->kws = (keywords *)malloc(sizeof(unsigned char) * 10 * i);
- strcpy(o->kws[0].words, "The First Data");
- strcpy(o->kws[1].words, "The Second Data");
- o->len = i;
- return 1;
- }
Python代碼如下:
- class keywords(Structure):
- _fields_ = [('words', c_char *10),]
- class outStruct(Structure):
- _fields_ = [('kws', POINTER(keywords)),
- ('len', c_int),]
- o = outStruct()
- dll.test(byref(o))
- print o.kws[0].words;
- print o.kws[1].words;
- print o.len
6、例子
說得天花亂墜,嘿嘿,還是看兩個實際的例子。
例子1:
這是一個GUID生成器,其實很多第三方的python庫已經有封裝好的庫可以調用,不過這得裝了那個庫才行,如果想直接調用一些API,對於python來說,也要借助一個第三方庫才行,這個例子比較簡單,就是用C++調用win32 API來產生GUID,然后python通過調用C++寫的dll來獲得這個GUID。
C++代碼如下:
- extern "C"__declspec(dllexport) char* newGUID();
- char* newGUID()
- {
- static char buf[64] = {0};
- statc GUID guid;
- if (S_OK == ::CoCreateGuid(&guid))
- {
- _snprintf(buf, sizeof(buf),
- "%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X",
- guid.Data1,
- guid.Data2,
- guid.Data3,
- guid.Data4[0], guid.Data4[1],
- guid.Data4[2], guid.Data4[3],
- guid.Data4[4], guid.Data4[5],
- guid.Data4[6], guid.Data4[7]
- );
- ::MessageBox(NULL, buf, "GUID", MB_OK);
- }
- return (char*)buf;
- }
Python代碼如下:
- def CreateGUID():
- """
- 創建一個全局唯一標識符
- 類似:E06093E2-699A-4BF2-A325-4F1EADB50E18
- NewVersion
- """
- try:
- # dll path
- strDllPath = sys.path[0] + str(os.sep) + "createguid.dll"
- dll = CDLL(strDllPath)
- b = dll.newGUID()
- a = c_char_p(b)
- except Exception, error:
- print error
- return ""
- return a.value
例子2:
這個例子是調用kernel32.dll中的createprocessA函數來啟動一個記事本進程
- # -*- coding:utf-8 -*-
- from ctypes import *
- # 定義_PROCESS_INFORMATION結構體
- class _PROCESS_INFORMATION(Structure):
- _fields_ = [('hProcess', c_void_p),
- ('hThread', c_void_p),
- ('dwProcessId', c_ulong),
- ('dwThreadId', c_ulong)]
- # 定義_STARTUPINFO結構體
- class _STARTUPINFO(Structure):
- _fields_ = [('cb',c_ulong),
- ('lpReserved', c_char_p),
- ('lpDesktop', c_char_p),
- ('lpTitle', c_char_p),
- ('dwX', c_ulong),
- ('dwY', c_ulong),
- ('dwXSize', c_ulong),
- ('dwYSize', c_ulong),
- ('dwXCountChars', c_ulong),
- ('dwYCountChars', c_ulong),
- ('dwFillAttribute', c_ulong),
- ('dwFlags', c_ulong),
- ('wShowWindow', c_ushort),
- ('cbReserved2', c_ushort),
- ('lpReserved2', c_char_p),
- ('hStdInput', c_ulong),
- ('hStdOutput', c_ulong),
- ('hStdError', c_ulong)]
- NORMAL_PRIORITY_CLASS = 0x00000020 #定義NORMAL_PRIORITY_CLASS
- kernel32 = windll.LoadLibrary("kernel32.dll") #加載kernel32.dll
- CreateProcess = kernel32.CreateProcessA #獲得CreateProcess函數地址
- ReadProcessMemory = kernel32.ReadProcessMemory #獲得ReadProcessMemory函數地址
- WriteProcessMemory = kernel32.WriteProcessMemory #獲得WriteProcessMemory函數地址
- TerminateProcess = kernel32.TerminateProcess
- # 聲明結構體
- ProcessInfo = _PROCESS_INFORMATION()
- StartupInfo = _STARTUPINFO()
- fileName = 'c:/windows/notepad.exe' # 要進行修改的文件
- address = 0x0040103c # 要修改的內存地址
- strbuf = c_char_p("_") # 緩沖區地址
- bytesRead = c_ulong(0) # 讀入的字節數
- bufferSize = len(strbuf.value) # 緩沖區大小
- # 創建進程
- CreateProcess(fileName, 0, 0, 0, 0, NORMAL_PRIORITY_CLASS,0, 0, byref(StartupInfo), byref(ProcessInfo))