先上最终代码
# -*- coding: utf-8 -*-
from ctypes import *
import json
dll = WinDLL("./XoceDat.dll")
dll.getkey.argtypes = [c_char_p]
dll.getkey.restype = c_char_p
key = 'dcfeeda368254029a25307d9a6be457a'
key = key.encode('gb2312')
key_b = create_string_buffer(key)
res = dll.getkey(key_b)
res = res.decode('gb2312', errors='ignore')
print(res)
res = json.loads(res)
刚开始调用,报不是win32程序
之类的错误,Google一下发现是因为python是64位,dll是32位
果断下一个32位python继续
结果函数调用成功了,返回一个整形数字
Google again 发现需要指定格式dll.getkey.restype = c_char_p
但返回的报错
因该是传参的时候参数类型错误dll.getkey.argtypes = [c_char_p]
精益论坛例程
#-*-coding:utf-8-*-
import ctypes #引入python调用dll的支持库
dll = ctypes.WinDLL("test.dll")#引入Dll 返回对象
#操作dll内部方法用dll.
#操作ctypes支持库用ctypes.
#python ctypes支持库引入dll时
#并不知道dll中所定义的方法返回值类型以及参数类型
#调用之前需要手动定义1下
#以下为定义参数类型 使用关键字argtypes
dll.test_str.argtypes = [ctypes.c_char_p]#定义方法的参数为长字符串
dll.test_int.argtypes = [ctypes.c_int,ctypes.c_int]#定义方法的参数为整数型
dll.test_bool.argtypes = [ctypes.c_bool]#定义方法的参数为逻辑型
#以下为定义返回值类型 使用关键字restype
dll.test_str.restype = ctypes.c_char_p
dll.test_int.restype = ctypes.c_int
dll.test_bool.restype = ctypes.c_bool
#设置几个变量
p = ctypes.create_string_buffer(b"Hello")#创建1个长字符串
s = ctypes.c_bool(True)#创建1个逻辑型变量
#调用dll中的函数并得到返回值
txt_return_str = ctypes.string_at(dll.test_str(p))
#如不是长字符串则只能传入第1个字符
#比如Hello只能传入H
txt_return_int = dll.test_int(5,8)
txt_return_bool = dll.test_bool(s)
#设置输出编码并输出
print(txt_return_str.decode('utf-8'))
print(txt_return_int)
print(txt_return_bool)#0为false 1为true