Gar*_*Jax 13 c python struct ctypes
我正在time_t使用python ctypes模块访问包含一些字段的C结构.
鉴于其非完全可移植性,我不能静态地定义这些字段c_int或c_long类型.
如何定义它们以使我的代码可移植?
示例C结构定义:
#import <sys/types.h>
#import <time.h>
typedef struct my_struct {
time_t timestap;
uint16_t code;
};
Run Code Online (Sandbox Code Playgroud)
各自的python ctypes结构:
from ctypes import *
c_time = ? # What do I have to put here?
class MyStruct(Structure):
_fields_ = [
('timestamp', c_time),
('code', c_int16),
]
Run Code Online (Sandbox Code Playgroud)
最好的选择是检查脚本运行的系统,并选择要使用的整数类型。就像是,
if sys.platform == 'win32':
time_t = ctypes.c_uint64
# ...
Run Code Online (Sandbox Code Playgroud)
最重要的是time_t标准中没有定义。这取决于操作系统和编译器。因此,您在 Python 脚本中的定义time_t取决于您正在与之交互的 DLL/so。