1. 程式人生 > >python呼叫dll檔案介面

python呼叫dll檔案介面

轉載

Python中某些時候需要C做效率上的補充,在實際應用中,需要做部分資料的互動。使用python中的ctypes模組可以很方便的呼叫windows的dll(也包括linux下的so等檔案),下面將詳細的講解這個模組(以windows平臺為例子),當然我假設你們已經對windows下怎麼寫一個DLL是沒有問題的。
  
引入ctypes庫 

  1. from ctypes import *   
假設你已經有了一個的DLL(名字是add.dll),且該DLL有一個符合cdecl(這裡強調呼叫約定是因為,stdcall呼叫約定和cdecl呼叫約定宣告的匯出函式,在使用python載入時使用的載入函式是不同的,後面會有說明)呼叫約定的匯出函式Add。
建立一個Python檔案DllCall.py測試: 
  1. from ctypes import *  
  2. dll = CDLL("add.dll")  
  3. print dll.Add(1102)  
結果:103 
  
上面是一個簡單的例子。下面簡單聊一下呼叫流程: 
1、載入DLL 
上面已經說過,載入的時候要根據你將要呼叫的函式是符合什麼呼叫約定的。 
stdcall呼叫約定:兩種載入方式 
  1. Objdll = ctypes.windll.LoadLibrary("dllpath")  
  2. Objdll = ctypes.WinDLL("dllpath")   
cdecl呼叫約定:也有兩種載入方式 
  1. Objdll = ctypes.cdll.LoadLibrary("dllpath")  
  2. Objdll = ctypes.CDLL("dllpath")  
  3. <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型別的指標。
  1. intPara = c_int(9)  
  2. dll.sub(23102, byref(intPara))  
  3. print intPara.value  
如果是要傳入一個char緩衝區指標,和緩衝區長度,方法至少有四種: 
  1. # 方法1
  2. szPara = create_string_buffer('/0'*100)  
  3. dll.PrintInfo(byref(szPara), 100);  
  4. print szPara.value  
  5. # 方法2
  6. sBuf = 'aaaaaaaaaabbbbbbbbbbbbbb'
  7. pStr = c_char_p( )  
  8. pStr.value = sBuf  
  9. #pVoid = ctypes.cast( pStr, ctypes.c_void_p ).value
  10. dll.PrintInfo(pStr, len(pStr.value))  
  11. print pStr.value  
  12. # 方法3
  13. strMa = "/0"*20
  14. FunPrint  = dll.PrintInfo  
  15. FunPrint.argtypes = [c_char_p, c_int]  
  16. #FunPrint.restypes = c_void_p
  17. nRst = FunPrint(strMa, len(strMa))  
  18. print strMa,len(strMa)  
  19. # 方法4
  20. pStr2 = c_char_p("/0")  
  21. print pStr2.value  
  22. #pVoid = ctypes.cast( pStr, ctypes.c_void_p ).value
  23. dll.PrintInfo(pStr2, len(pStr.value))  
  24. 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屬性訪問。 
  1. pchar = dll.getbuffer()  
  2. szbuffer = c_char_p(pchar)  
  3. print szbuffer.value  

5、處理C中的結構體型別 
為什麼把這個單獨提出來說呢,因為這個是最麻煩也是最複雜的,在python裡面申明一個類似c的結構體,要用到類,並且這個類必須繼承自Structure。 
先看一個簡單的例子: 
C裡面dll的定義如下: 
  1. typedefstruct _SimpleStruct  
  2. {  
  3.     int    nNo;  
  4.     float  fVirus;  
  5.     char   szBuffer[512];  
  6. } SimpleStruct, *PSimpleStruct;  
  7. typedefconst SimpleStruct*  PCSimpleStruct;  
  8. extern"C"int__declspec(dllexport) PrintStruct(PSimpleStruct simp);  
  9. int PrintStruct(PSimpleStruct simp)  
  10. {  
  11.     printf ("nMaxNum=%f, szContent=%s", simp->fVirus, simp->szBuffer);  
  12. return simp->nNo;  
  13. }  

Python的定義: 
  1. from ctypes import *  
  2. class SimpStruct(Structure):  
  3.     _fields_ = [ ("nNo", c_int),  
  4.               ("fVirus", c_float),  
  5.               ("szBuffer", c_char * 512)]  
  6. dll = CDLL("AddDll.dll")  
  7. simple = SimpStruct();  
  8. simple.nNo = 16
  9. simple.fVirus = 3.1415926
  10. simple.szBuffer = "magicTong/0"
  11. print dll.PrintStruct(byref(simple))  

上面例子結構體很簡單,但是如果結構體裡面有指標,甚至是指向結構體的指標,處理起來會複雜很多,不過Python裡面也有相應的處理方法,下面這個例子來自網上,本來想自己寫個,懶得寫了,能說明問題就行:
C程式碼如下: 
  1. typedefstruct
  2. {  
  3. char words[10];  
  4. }keywords;  
  5. typedefstruct
  6. {  
  7. keywords *kws;  
  8. unsigned int len;  
  9. }outStruct;  
  10. extern"C"int__declspec(dllexport) test(outStruct *o);  
  11. int test(outStruct *o)  
  12. {  
  13. unsigned int i = 4;  
  14. o->kws = (keywords *)malloc(sizeof(unsigned char) * 10 * i);  
  15. strcpy(o->kws[0].words, "The First Data");  
  16. strcpy(o->kws[1].words, "The Second Data");  
  17. o->len = i;  
  18. return 1;  
  19. }  
Python程式碼如下: 
  1. class keywords(Structure):  
  2.         _fields_ = [('words', c_char *10),]  
  3. class outStruct(Structure):  
  4.         _fields_ = [('kws', POINTER(keywords)),  
  5.                     ('len', c_int),]  
  6. o = outStruct()  
  7. dll.test(byref(o))  
  8. print o.kws[0].words;  
  9. print o.kws[1].words;  
  10. print o.len  

6、例子 
說得天花亂墜,嘿嘿,還是看兩個實際的例子。 
例子1: 
這是一個GUID生成器,其實很多第三方的python庫已經有封裝好的庫可以呼叫,不過這得裝了那個