溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

python引用dll的方法是什么

發(fā)布時(shí)間:2020-08-05 14:26:48 來(lái)源:億速云 閱讀:135 作者:小新 欄目:編程語(yǔ)言

這篇文章給大家分享的是有關(guān)python引用dll的方法是什么的內(nèi)容。小編覺(jué)得挺實(shí)用的,因此分享給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧。

在python中調(diào)用dll文件中的接口比較簡(jiǎn)單,實(shí)例代碼如下:

如我們有一個(gè)test.dll文件,內(nèi)部定義如下:

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

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

1.

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

2.

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

其中ctypes.windll為ctypes.WinDll類的一個(gè)對(duì)象,已經(jīng)在ctypes模塊中定義好的。在test.dll中有test接口,可直接用dll調(diào)用即可

nRst = dll.test( )
print nRst

由于在test這個(gè)接口中需要傳遞兩個(gè)參數(shù),一個(gè)是void類型的指針,它指向一個(gè)緩沖區(qū)。一個(gè)是該緩沖區(qū)的長(zhǎng)度。因此我們要獲取到python中的字符串的指針和長(zhǎng)度。

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

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

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

由于接口中定義的是cdecl格式的調(diào)用,所以在python中也需要用相應(yīng)的類型。

1.

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

2.

import ctypes
dll = ctypes.CDll( 'test.dll' )

感謝各位的閱讀!關(guān)于python引用dll的方法是什么就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,讓大家可以學(xué)到更多知識(shí)。如果覺(jué)得文章不錯(cuò),可以把它分享出去讓更多的人看到吧!

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI