【问题标题】:python cffi parsing error when defining a struct定义结构时python cffi解析错误
【发布时间】:2016-01-20 20:07:27
【问题描述】:

我正在尝试使用 python-cffi 来包装 C 代码。以下example_build.py 显示了尝试包装lstat() 调用:

import cffi

ffi = cffi.FFI()
ffi.set_source("_cstat",
        """
        #include <sys/types.h>
        #include <sys/stat.h>
        #include <unistd.h>
        """,
        libraries=[])

ffi.cdef("""
        struct stat {
            mode_t  st_mode;
            off_t   st_size;
            ...;
        };
        int lstat(const char *path, struct stat *buf);
""")


if __name__ == '__main__':
    ffi.compile()

编译时python example_build.py 会报错mode_t st_mode 的解析错误。

cffi.api.CDefError: cannot parse "mode_t  st_mode;"
:4:13: before: mode_t

manual 给出的类似示例没有任何问题。我错过了什么? TIA。

【问题讨论】:

    标签: python python-cffi


    【解决方案1】:

    您需要告知 CFFI mode_toff_t 是一些整数类型。最简单的方法是首先在 cdef() 中添加这些行:

    typedef int... mode_t;   /* means "mode_t is some integer type" */
    typedef int... off_t;
    

    【讨论】:

    • 实际类型宽度可能不同。请不要只定义为 INT
    • @socketpair: 不,typedef int... off_t; 语法的重点,加上省略号,正是要求 CFFI 为您找到真正的类型宽度。这并不意味着“完全使用 int”。
    猜你喜欢
    • 2019-01-20
    • 2021-05-28
    • 1970-01-01
    • 2019-07-30
    • 2013-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-15
    相关资源
    最近更新 更多