python定义结构时cffi解析错误

python cffi parsing error when defining a struct

我正在尝试使用 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.

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

中添加这些行
typedef int... mode_t;   /* means "mode_t is some integer type" */
typedef int... off_t;