python调用dll
- IT科技
- 关注:2.17W次
<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
由于在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 ' )
- 文章版权属于文章作者所有,转载请注明 https://dongkepu.com/itkeji/djlkxj.html