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

ctypes 的问题

  •  
  •   ryanking8215 ·
    ryanking8215 · 2014-12-25 14:03:08 +08:00 · 2371 次点击
    这是一个创建于 3402 天前的主题,其中的信息可能已经有所发展或是发生改变。
    有一个2进制网络协议,用struct模块,通过pack(),unpack()和bytes交互。
    但是想和c一样,定义一个struct,不通过struct模块,行不行呢?
    比如:
    class T(ctypes.Structure):
    _fields_=[('x',ctypes.c_uint)]

    等同于c的:
    struct T {
    unsigned int x;
    };

    t = T()
    如何让t直接得到bytes的数据,和转成bytes呢?

    使用 f = open("kk",'wb'); f.write(t); f.close()
    能把t的二进制数据直接写入文件,但是sock.write()就不行,说不是byte-ish类型。
    不知其中原委,愿闻其详
    5 条回复    2014-12-29 08:51:32 +08:00
    timonwong
        1
    timonwong  
       2014-12-25 15:04:32 +08:00
    因为 ctypes.Structure 类型是可以转换为 "buffer" 类型的

    然后 file 类型支持写入 "buffer" 类型,因此可行。
    fileobject.write(str or buffer)

    bytes(buffer(t))
    ryanking8215
        2
    ryanking8215  
    OP
       2014-12-25 15:33:19 +08:00
    @timonwong 忘了说了,我用的是python3.4,没有buffer类型。发现用bytes(t)可以直接得到二进制数据。bytes->t有什么办法吗?我现在用struct模块转,但我觉得应该有更简单的办法。
    ryanking8215
        3
    ryanking8215  
    OP
       2014-12-25 15:59:07 +08:00
    可以这样:
    b=b'1111'
    PT = ctypes.POINTER(T)
    pt = ctypes.cast(b,PT)
    print(pt.contents)

    通过ctypes.cast,将bytes对象指向的内存变为T *类型的,然后按照T类型取出内存中的数据。
    fghzpqm
        4
    fghzpqm  
       2014-12-26 15:10:07 +08:00   ❤️ 1
    @ryanking8215 感觉你在找 Construct 这样的东西。http://construct.readthedocs.org/en/latest/
    ryanking8215
        5
    ryanking8215  
    OP
       2014-12-29 08:51:32 +08:00
    @fghzpqm 是这么个东东,不过我用自己的方法也可以转了
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   942 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 21:04 · PVG 05:04 · LAX 14:04 · JFK 17:04
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.