Python 中如何向 C API 函数传递中文字符串?(ctypes)

2017-08-26 20:16:27 +08:00
 explist

from ctypes import CDLL

c = CDLL("msvcrt.dll")

c.printf('a=%d'.encode(),1) #这样正确

c.printf('中国=%d'.encode(),1) # 这里不能正确显示 @: a 浜?1

#----------又如------------

int testFile(const char* filename); /* 打开文件进行一些操作(文件名可能含有中文字符) */

path = r"c:\中文测试.txt" #python 中

API.testFile(path.encode()) # 会出现打开文件出错提示

3032 次点击
所在节点    Python
5 条回复
albertofwb
2017-08-26 20:23:38 +08:00
我复制了你的代码在本机测试,中文没有问题
https://www.jianguoyun.com/p/DZCa_n4Qhp-3BhiJrzM

win10
git-bash.exe
python3.4.3
explist
2017-08-26 20:26:46 +08:00
我这里输出:
涓浗=1
albertofwb
2017-08-26 20:26:54 +08:00
我明白了,因为 python 默认的 str.encode() 是 utf8,而我之所以成功是因为 git-bash  本身就是 utf8 环境
如果你在 windows 的 cmd 中运行这段代码,由于 cmd 默认编码是 gbk,所以你代码这样改之后就应该没问题
```python
c.printf('老铁看这里 a=%d'.encode('gbk'),1)
```
explist
2017-08-26 20:32:00 +08:00
我想知道如何传递 path 给 C API.testFile()这个库函数?
explist
2017-08-26 20:35:44 +08:00
呵呵,成功了
path.encode('gbk')

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/386011

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX