推荐学习书目
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
css3
V2EX  ›  Python

Python 如何给 C 函数传 json 字符串?

  •  
  •   css3 · Feb 17, 2019 · 2835 views
    This topic created in 2642 days ago, the information mentioned may be changed or developed.

    调用的都是同一个 C 函数,python 用的 ctypes

    // c 语言中调用是这样
    Init("{\"a\":\"../../av\", \"b\":\"../../bv\"}")
    
    #如果用 python 调用 init 函数时,应该传递啥样的 json 字符串?这样不行😂,提示 expected key string
    Init('{"a": "../av", "b": "../bv"}')
    
    Supplement 1  ·  Feb 18, 2019
    C 函数参数类型是:const char *
    10 replies    2019-02-19 19:54:59 +08:00
    lynskylate
        1
    lynskylate  
       Feb 17, 2019 via Android
    ...你先确认下你 python 版本,c 默认接受是 char*的话,ctypes 传的参数必须是 bytes
    xd314697475
        2
    xd314697475  
       Feb 17, 2019
    你把 c 的函数接口类型确定了
    Init ( char *x )

    然后 python 里

    s="{\"a\":\"../../av\", \"b\":\"../../bv\"}"

    .Init ( s )
    ysc3839
        3
    ysc3839  
       Feb 17, 2019
    试试 Init('{"a": "../av", "b": "../bv"}'.encode())
    如果可以的话把完整代码发上来吧。
    css3
        4
    css3  
    OP
       Feb 18, 2019
    @xd314697475 这样肯定不行啊,语法都是错误,python 双引号中,不能再用双引号啊
    css3
        5
    css3  
    OP
       Feb 18, 2019
    @xd314697475 忽略 4 楼我说的,这样是不行的,就是我主帖里边的报的错:expected key string
    css3
        6
    css3  
    OP
       Feb 18, 2019
    @ysc3839 很棒,这样是可行的👍👍👍👍
    ysc3839
        7
    ysc3839  
       Feb 18, 2019 via Android
    @css3 忘记了,应该可以更简单,试试
    Init(b'{"a": "../av", "b": "../bv"}')
    css3
        8
    css3  
    OP
       Feb 18, 2019
    @ysc3839 👍👍👍👍👍👍👍👍👍👍👍👍也可以,多谢,顺便再问一下,假如 C 函数返回一个句柄,用 python 调用这个函数的时候,应该怎么拿这个句柄呢?
    ysc3839
        9
    ysc3839  
       Feb 18, 2019 via Android
    @css3 什么句柄?发代码看看?
    css3
        10
    css3  
    OP
       Feb 19, 2019
    @ysc3839 摸索了下,搞定啦,多谢了😁
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   5464 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 48ms · UTC 08:49 · PVG 16:49 · LAX 01:49 · JFK 04:49
    ♥ Do have faith in what you're doing.