python引用DLL檔案的方法

來源:互聯網
上載者:User
本文執行個體講述了python引用DLL檔案的方法。分享給大家供大家參考。具體分析如下:

在python中調用dll檔案中的介面比較簡單,如我們有一個test.dll檔案,內部定義如下:

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

在python中我們可以用以下兩種方式載入

1.

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

2.

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

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

nRst = dll.test( )print nRst

由於在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' )

希望本文所述對大家的Python程式設計有所協助。

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.