在python中调用dll文件,实例代码如下:
1:建立C语言文件,假如名字叫做dlltest.c:
#include "stdlib.h"
__declspec(dllexport) int __stdcall test( void* p, int len)
{
return len;
}
编译链接,生成dlltest.dll
注:打开cmd dos窗口,把工作路径调整到dlltext.c所在路径,输入cl -LD dlltest.c -libtest.dll,生成的dlltest.dll也没问题
2:建立python文件,假如名字叫做pyu.py,把下面代码1粘入pyu.py
#代码1
dll = ctypes.windll.LoadLibrary( 'dlltest.dll ')
sBuf = 'abc'
pStr = ctypes.c_char_p( )
pStr.value = sBuf
pVoid = ctypes.cast( pStr, ctypes.c_void_p ).value
nRst = dll.test( pVoid, 10 )
print nRst
或者还有一种方式调用dll文件,即用代码2所示方法:
#代码2
import ctypes
from ctypes import *
dll = ctypes.WinDLL( 'dlltest.dll ')
sBuf = 'abc'
pStr = ctypes.c_char_p( )
pStr.value = sBuf
pVoid = ctypes.cast( pStr, ctypes.c_void_p ).value
nRst = dll.test( pVoid, 10 )
print nRst
讲解: ctypes.WinDLL 和 ctypes.windll.LoadLibrary可以互换是因为,ctypes.windll为ctypes.WinDLL类的一个对象
3:运行python文件,搞定
注意:
1)python争取用32位的,生成的dll文件一般情况下都是32为的,64位的python不能支持32位的dll文件;
2)C文件中的函数声明如果是__stdcall或者是__cdcel的话,python中的调用方式一定要对应,要不然也出错,具体方式如下:
#include "stdlib.h"
__declspec(dllexport) int __cdecl test( void* p, int len)
{
return len;
}
由于接口中定义的是cdecl格式的调用,所以在python中也需要用相应的类型
import ctypes
dll = ctypes.cdll.LoadLibrary( 'dlltest.dll' )
import ctypes
dll = ctypes.CDLL( 'dlltest.dll' )