Skip to main content
 首页 » 编程设计

定义结构时python cffi解析错误

2025年05月04日43duanxz

我正在尝试使用 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_t和off_t是一些整数类型。最简单的方法是首先在 cdef() 中添加这些行:

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