欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

python引用DLL文件的方法

 更新時間:2015年05月11日 15:43:12   作者:像風(fēng)一樣的自由  
這篇文章主要介紹了python引用DLL文件的方法,涉及Python調(diào)用dll文件的相關(guān)技巧,需要的朋友可以參考下

本文實(shí)例講述了python引用DLL文件的方法。分享給大家供大家參考。具體分析如下:

在python中調(diào)用dll文件中的接口比較簡單,如我們有一個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類的一個對象,已經(jīng)在ctypes模塊中定義好的。在test.dll中有test接口,可直接用dll調(diào)用即可

nRst = dll.test( )
print nRst

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

#方法一:
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' )

希望本文所述對大家的Python程序設(shè)計(jì)有所幫助。

相關(guān)文章

最新評論