V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
推荐学习书目
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 · Aug 26, 2017 · 3655 views
    This topic created in 3167 days ago, the information mentioned may be changed or developed.

    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 replies    2017-08-26 20:35:44 +08:00
    albertofwb
        1
    albertofwb  
       Aug 26, 2017
    我复制了你的代码在本机测试,中文没有问题
    https://www.jianguoyun.com/p/DZCa_n4Qhp-3BhiJrzM

    win10
    git-bash.exe
    python3.4.3
    explist
        2
    explist  
    OP
       Aug 26, 2017
    我这里输出:
    涓浗=1
    albertofwb
        3
    albertofwb  
       Aug 26, 2017   ❤️ 1
    我明白了,因为 python 默认的 str.encode() 是 utf8,而我之所以成功是因为 git-bash  本身就是 utf8 环境
    如果你在 windows 的 cmd 中运行这段代码,由于 cmd 默认编码是 gbk,所以你代码这样改之后就应该没问题
    ```python
    c.printf('老铁看这里 a=%d'.encode('gbk'),1)
    ```
    explist
        4
    explist  
    OP
       Aug 26, 2017
    我想知道如何传递 path 给 C API.testFile()这个库函数?
    explist
        5
    explist  
    OP
       Aug 26, 2017
    呵呵,成功了
    path.encode('gbk')
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   1191 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 36ms · UTC 23:21 · PVG 07:21 · LAX 16:21 · JFK 19:21
    ♥ Do have faith in what you're doing.