推荐学习书目
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 · Dec 25, 2014 · 3208 views
    This topic created in 4229 days ago, the information mentioned may be changed or developed.
    有一个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 replies    2014-12-29 08:51:32 +08:00
    timonwong
        1
    timonwong  
       Dec 25, 2014
    因为 ctypes.Structure 类型是可以转换为 "buffer" 类型的

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

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

    通过ctypes.cast,将bytes对象指向的内存变为T *类型的,然后按照T类型取出内存中的数据。
    fghzpqm
        4
    fghzpqm  
       Dec 26, 2014   ❤️ 1
    @ryanking8215 感觉你在找 Construct 这样的东西。http://construct.readthedocs.org/en/latest/
    ryanking8215
        5
    ryanking8215  
    OP
       Dec 29, 2014
    @fghzpqm 是这么个东东,不过我用自己的方法也可以转了
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2909 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 41ms · UTC 05:45 · PVG 13:45 · LAX 22:45 · JFK 01:45
    ♥ Do have faith in what you're doing.