python调用dll
在python中调用dll文件中的接口比较简单,实例代码如下:
如我们有一个test.dll文件,内部定义如下:
extern"C"
{
int__stdcalltest(void*p,intlen)
{
returnlen;
}
}
在python中我们可以用以下两种方式载入
1.
importctypes
dll=ctypes.windll.LoadLibrary('test.dll')
2.
importctypes
dll=ctypes.WinDll('test.dll')
其中ctypes.windll为ctypes.WinDll类的一个对象,已经在ctypes模块中定义好的。在test.dll中有test接口,可直接用dll调用即可
nRst=dll.test()
printnRst
由于在test这个接口中需要传递两个参数,一个是void类型的指针,它指向一个缓冲区。一个是该缓冲区的长度。因此我们要获取到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__cdecltest(void*p,intlen)
{
returnlen;
}
}
由于接口中定义的是cdecl格式的调用,所以在python中也需要用相应的类型
1.
importctypes
dll=ctypes.cdll.LoadLibrary('test.dll')
##注:一般在linux下为test.o文件,同样可以使用如下的方法:
##dll=ctypes.cdll.LoadLibrary('test.o')
2.
importctypes
dll=ctypes.CDll('test.dll')
以上内容为大家介绍了python调用dll,希望对大家有所帮助,如果想要了解更多Python相关知识,请关注IT培训机构:千锋教育。http://www.mobiletrain.org/

相关推荐HOT
更多>>
python怎么输入多变量
Python同时输入多个值 1.同时输入多个字符串,字符串间以逗号/空...详情>>
2023-11-12 23:43:43
python岗位主要做什么工作?
python的工作岗位还是很多的,涉及的工作方向也很广,下面举一些常见的岗位,大家可以参考:Web应用开发Python经常被用于Web开发。例如,通过mo...详情>>
2023-11-12 23:05:27
python能做网站吗?
python可以做网站,Python有很多优秀的网站框架,可以非常快速的建一个网站。比如django之类的框架。Django、TurboGears、Eurasia、UliWeb等:...详情>>
2023-11-12 21:47:07
python中的int是什么意思?
python中的int()函数用于将一个字符串或数字转换为整型。语法以下是int()方法的语法:classint(x,base=10)参数x--字符串或数字。base--进制数,...详情>>
2023-11-12 21:21:30