V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
explist
V2EX  ›  Python

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

  •  
  •   explist · 2017-08-26 20:16:27 +08:00 · 3014 次点击
    这是一个创建于 2439 天前的主题,其中的信息可能已经有所发展或是发生改变。

    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()) # 会出现打开文件出错提示

    5 条回复    2017-08-26 20:35:44 +08:00
    albertofwb
        1
    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
        2
    explist  
    OP
       2017-08-26 20:26:46 +08:00
    我这里输出:
    涓浗=1
    albertofwb
        3
    albertofwb  
       2017-08-26 20:26:54 +08:00   ❤️ 1
    我明白了,因为 python 默认的 str.encode() 是 utf8,而我之所以成功是因为 git-bash  本身就是 utf8 环境
    如果你在 windows 的 cmd 中运行这段代码,由于 cmd 默认编码是 gbk,所以你代码这样改之后就应该没问题
    ```python
    c.printf('老铁看这里 a=%d'.encode('gbk'),1)
    ```
    explist
        4
    explist  
    OP
       2017-08-26 20:32:00 +08:00
    我想知道如何传递 path 给 C API.testFile()这个库函数?
    explist
        5
    explist  
    OP
       2017-08-26 20:35:44 +08:00
    呵呵,成功了
    path.encode('gbk')
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2245 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 32ms · UTC 02:38 · PVG 10:38 · LAX 19:38 · JFK 22:38
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.