Python 中 off_t 的适当映射的便携式确定是否可以用于 ctypes?

Is a portable determination of appropriate mapping for off_t in Python for use in ctypes possible?

背景:POSIX-defined off_t data type is a signed integer of variable-size depending on the environment。对于 64 位构建环境,它似乎始终是 64 位 off_t。对于 32 位系统,off_t 的大小取决于环境(通常由 _FILE_OFFSET_BITS 和相关控制)。

我正在使用 Python 的 ctypes to access some library calls for functions that use the off_t data type. ctypes does not have a type for off_t so mapping such an API via a Structure,否则需要选择 ctypes[= 定义的一些其他类型37=],即c_intc_int32c_int64c_longc_longlong.

之一

在四处寻找其他人的解决方案时,我看到了各种各样的解决方案,其中大多数是猜测并且仅限于一种环境,其中一些完全错误(使用无符号类型)和 none其中便携。

对于给定的 Python 解释器的构建,是否有一种健壮的、可移植的方法来确定 off_t 的大小?

谢谢!

标准中不支持此功能,正如您自己指出的那样,它会根据用于编译 库的标志在 32 位机器上有所不同, 不是 Python。 (也就是说,你需要知道你正在使用的库例程是否是用-D_FILE_OFFSET_BITS=64编译的......)

GCC 似乎非常一致地将 off_t 定义为 long int。所以这可能是 "safest" 的选择。或者你可以默认使用 64 位。在任何一种情况下,覆盖行为并指定位数的选项都可能很有价值。

是否有可以调用的函数 return 和 off_t?也许你可以用 0xFF 填充缓冲区,然后 seek(0)ftell() 看看写入了多少个零?

我不是 100% 确定,但 sysconfig 可能就是这样(对于 python 3.2+):

Python 3.9.1 (default, Dec  8 2020, 02:26:20) 
[GCC 9.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import sysconfig
>>> sysconfig.get_config_var('SIZEOF_OFF_T')
8
>>> sysconfig.get_config_var('SIZEOF_PID_T')
4