1、无参
动态链接库:
void SayHello()
{
MessageBox(NULL,
TEXT("你好你好~~~"),
TEXT("你好"),
MB_OK);
}
加载dll,调用函数
from ctypes import *
lib = CDLL ("e:\\Dll1.dll")
lib.SayHello()
2、有参
from ctypes import *
lib = CDLL ("e:\\Dll1.dll")
lib.StrAppend('你好')
ret = lib.IntAdd(3,4)
print(ret)
IntAdd 和 StrAppend, 我们直接使用了Python对象作为参数传入。
实际上,底层的ctypes库调用c语言库,不能直接传递python对象的,需要转化为c语言接口对应的类型。
它会根据我们使用的python对象类型,猜测应该转化为什么类型的数据。
Python数据对象和C语言的数据对象的对应关系见 ctypes — A foreign function library for Python — Python 3.10.4 documentation
特别要注意 w_char 和 char 的区别,前者对应python 3中的 字符串, 后者对应 字节串
3、指定参数类型
from ctypes import *
lib = CDLL ("e:\\Dll1.dll")
lib.StrAppend.argtypes = [c_wchar_p]
lib.StrAppend('你好')
也可以
lib.StrAppend(c_wchar_p('你好'))
4、指定返回值类型
from ctypes import *
lib = CDLL ("e:\\Dll1.dll")
ret = lib.IntAdd(3,4)
print(ret)
lib.StrAppend.restype = c_wchar_p
ret2 = lib.StrAppend('你好')
print(ret2)
lib.BytesAppend.restype = c_char_p
ret3 = lib.BytesAppend(b'\x39\x99')
print(ret3)
类型暗示
3.5版本开始推出type hint功能
def greeting(name: str) -> str:
return 'Hello ' + str(name)
暗示name参数类型是str,greeting函数返回值类型是str
文章出处登录后可见!
已经登录?立即刷新