声明包含在Python CFFI time_t的场结构 [英] Declare struct containing time_t field in Python CFFI

查看:720
本文介绍了声明包含在Python CFFI time_t的场结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用CFFI叫Python的C函数返回一个结构。该结构与 time_t的元素定义。我如何声明结构来CFFI,这样我可以在Python访问它?

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>")

这给出了一个错误:

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

它注释掉行 time_t的后编译tv_sec; ,但你当然不能访问 tv_sec 字段。 presumably,CFFI的C语言解析器不支持的typedef。你不能只是替换 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.

推荐答案

我担心是没有很好的答案。你需要写的typedef长time_t的; 或类似的,假设的time_t是永远不变的尺寸一样长。如果code应该是移植到平台上,其中time_t的可能是不同的,那么你就需要分别得到大小:

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

这篇关于声明包含在Python CFFI time_t的场结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆