You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python3调用Windows DLL传递const char*触发ctypes.ArgumentError问题求助

问题原因及解决方法

错误原因

你的Python代码中,fileName是Python默认的Unicode字符串(str类型),但DLL函数PublicOpenFile的参数是const char*,对应ctypes里的c_char_p,需要传入字节串(bytes类型),类型不匹配导致报错。

解决方法

把字符串转换为字节串,有两种常见方式:

方式1:在字符串前加b前缀

直接定义字节串格式的文件名:

fileName = b"TheOutput.txt"

方式2:用encode()方法转换

如果文件名是动态生成的,通过encode()将Unicode字符串转为UTF-8字节串:

fileName = "TheOutput.txt".encode('utf-8')

修正后的完整代码

import ctypes
lib = ctypes.cdll.LoadLibrary('The.dll')
funcOpenFile = lib.PublicOpenFile
funcOpenFile.argtypes = [ctypes.c_char_p]
funcOpenFile.restype = ctypes.c_bool
fileName = b"TheOutput.txt"  # 改为字节串
result = funcOpenFile(fileName)
print(result)

额外说明:如果你的DLL需要支持含中文等非ASCII字符的路径,可以把DLL函数参数改为const wchar_t*,Python端对应使用ctypes.c_wchar_p,此时直接传入普通str字符串即可。

内容的提问来源于stack exchange,提问作者DannyPeet

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.12 18:52:02