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
css3
V2EX  ›  Python

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

  •  
  •   css3 · 2019-02-17 21:55:27 +08:00 · 2356 次点击
    这是一个创建于 1892 天前的主题,其中的信息可能已经有所发展或是发生改变。

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

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

    然后 python 里

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

    .Init ( s )
    ysc3839
        3
    ysc3839  
       2019-02-17 23:33:45 +08:00
    试试 Init('{"a": "../av", "b": "../bv"}'.encode())
    如果可以的话把完整代码发上来吧。
    css3
        4
    css3  
    OP
       2019-02-18 09:27:32 +08:00
    @xd314697475 这样肯定不行啊,语法都是错误,python 双引号中,不能再用双引号啊
    css3
        5
    css3  
    OP
       2019-02-18 09:28:27 +08:00
    @xd314697475 忽略 4 楼我说的,这样是不行的,就是我主帖里边的报的错:expected key string
    css3
        6
    css3  
    OP
       2019-02-18 09:39:55 +08:00
    @ysc3839 很棒,这样是可行的👍👍👍👍
    ysc3839
        7
    ysc3839  
       2019-02-18 10:24:01 +08:00 via Android
    @css3 忘记了,应该可以更简单,试试
    Init(b'{"a": "../av", "b": "../bv"}')
    css3
        8
    css3  
    OP
       2019-02-18 11:21:09 +08:00
    @ysc3839 👍👍👍👍👍👍👍👍👍👍👍👍也可以,多谢,顺便再问一下,假如 C 函数返回一个句柄,用 python 调用这个函数的时候,应该怎么拿这个句柄呢?
    ysc3839
        9
    ysc3839  
       2019-02-18 20:41:25 +08:00 via Android
    @css3 什么句柄?发代码看看?
    css3
        10
    css3  
    OP
       2019-02-19 19:54:59 +08:00
    @ysc3839 摸索了下,搞定啦,多谢了😁
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1121 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 18:47 · PVG 02:47 · LAX 11:47 · JFK 14:47
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.