網站首頁 學習教育 IT科技 金融知識 旅遊規劃 生活小知識 家鄉美食 養生小知識 健身運動 美容百科 遊戲知識 綜合知識
當前位置:趣知科普吧 > IT科技 > 

python調用dll

欄目: IT科技 / 發佈於: / 人氣:1.97W

<link rel="stylesheet" href="https://js.how234.com/third-party/SyntaxHighlighter/shCoreDefault.css" type="text/css" /><script type="text/javascript" src="https://js.how234.com/third-party/SyntaxHighlighter/shCore.js"></script><script type="text/javascript"> SyntaxHighlighter.all(); </script>

python調用dll怎麼操作?一起來看看小編今天的分享吧!

python調用dll有兩個方法,一是通過ctypes.windll.LoadLibrary()調用,二是通過ctypes.WinDll()調用。

例如假設我們存在一個test.dll文件

extern   " C "{ int  __stdcall test(  void *  p,  int  len){      return  len;} }

方法一:

import  ctypesdll  =  ctypes.windll.LoadLibrary(  ' test.dll '  )

方法二:

import  ctypesdll  =  ctypes.WinDll(  ' test.dll '  )

其中ctypes.windll為ctypes.WinDll類的一個對象,已經在ctypes模塊中定義好的。在test.dll中有test接口,可直接用dll調用即可。

nRst  =  dll.test( )print  nRst

python調用dll

由於在test這個接口中需要傳遞兩個參數,一個是void類型的指針,它指向一個緩衝區,一個是該緩衝區的長度。因此我們要獲取到python中的字符串的指針和長度。

#方法一:sBuf  =   ' aaaaaaaaaabbbbbbbbbbbbbb 'pStr  =  ctypes.c_char_p( )pStr.value  =  sBufpVoid  =  ctypes.cast( pStr, ctypes.c_void_p ).valuenRst  =  dll.test( pVoid, len( pStr.value) )#方法二:test  = dll.testtest.argtypes = [ctypes.c_char_p, ctypes.c_int]test.restypes = ctypes.c_intnRst = test(sBuf, len(sBuf))

如果修改test.dll中接口的定義如下:

extern   " C "{     int  __cdecl test(  void *  p,  int  len)    {         return  len;    }}

由於接口中定義的是cdecl格式的調用,所以在python中也需要用相應的類型:

1 .import  ctypesdll  =  ctypes.cdll.LoadLibrary(  ' test.dll '  )##注:一般在linux下為test.o文件,同樣可以使用如下的方法:## dll = ctypes.cdll.LoadLibrary('test.o')2 .import  ctypesdll  =  ctypes.CDll(  ' test.dll '  )

Tags:dll Python 調用