Declare struct containing time_t field in Python C

2019-07-04 22:05发布

I am using CFFI to call a C function from Python that returns a struct. The struct is defined with a time_t element. How do I declare the struct to CFFI so that I can access it from Python?

For example, I tried the following (to get the modified time of a file):

import cffi
ffi = cffi.FFI()
ffi.cdef("""
    // From POSIX
    struct timespec {
        time_t tv_sec;
        long tv_nsec;
        ...;
    };
    struct stat {
        struct timespec st_mtim;
        ...;
    };
    // From "man 2 lstat"
    int lstat(const char *path, struct stat *buf);
""")
stat = ffi.verify("#include <sys/stat.h>")

This gives an error:

cffi.api.CDefError: cannot parse "              time_t tv_sec;"                          
:5: before: time_t                                                                       

It does compile after commenting out the line time_t tv_sec;, but then of course you can't access the tv_sec field. Presumably, CFFI's C parser doesn't support typedefs. You can't just replace time_t with the actual type, since the type may be different on different platforms.

1条回答
甜甜的少女心
2楼-- · 2019-07-04 22:26

I fear there is no nice answer. You need to write typedef long time_t; or similar, assuming that time_t is always the same size as long. If the code is supposed to be portable to platforms where time_t might be different, then you would need to separately get the size:

ffi1 = cffi.FFI()
ffi1.cdef("""#define SIZE_OF_TIME_T ...""")
lib = ffi1.verify("""
   #include <sys/types.h>
   #define SIZE_OF_TIME_T  sizeof(time_t)
""")
size_of_time_t = lib.SIZE_OF_TIME_T
查看更多
登录 后发表回答