python呼叫dll檔案介面
阿新 • • 發佈:2019-01-25
轉載
在Python中某些時候需要C做效率上的補充,在實際應用中,需要做部分資料的互動。使用python中的ctypes模組可以很方便的呼叫windows的dll(也包括linux下的so等檔案),下面將詳細的講解這個模組(以windows平臺為例子),當然我假設你們已經對windows下怎麼寫一個DLL是沒有問題的。
引入ctypes庫
- from ctypes import *
建立一個Python檔案DllCall.py測試:
- from ctypes import *
- dll = CDLL("add.dll")
- print dll.Add(1, 102)
上面是一個簡單的例子。下面簡單聊一下呼叫流程:
1、載入DLL
上面已經說過,載入的時候要根據你將要呼叫的函式是符合什麼呼叫約定的。
stdcall呼叫約定:兩種載入方式
- Objdll = ctypes.windll.LoadLibrary("dllpath")
- Objdll = ctypes.WinDLL("dllpath")
- Objdll = ctypes.cdll.LoadLibrary("dllpath")
- Objdll = ctypes.CDLL("dllpath")
- <span style="font-family:Microsoft YaHei;">其實windll和cdll分別是WinDLL類和CDll類的物件。</span>
dll函式的_stdcall 和 _cdecl, stdcall是被呼叫者來進行棧的處理, cdecl是呼叫者進行棧的處理。
cdecl中每個呼叫者都要嵌入處理的程式碼,所以程式碼量會大一些。
但為什麼不都用stdcall。像printf這樣的函式,事先不知道需要的棧大小,需要用cdecl來處理
所以需要使用cdecl來呼叫
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
- # 方法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的定義如下:
- typedefstruct _SimpleStruct
- {
- int nNo;
- float fVirus;
- char szBuffer[512];
- } SimpleStruct, *PSimpleStruct;
- typedefconst 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程式碼如下:
- typedefstruct
- {
- char words[10];
- }keywords;
- typedefstruct
- {
- 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;
- }
- 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庫已經有封裝好的庫可以呼叫,不過這得裝了那個