【发布时间】:2020-10-03 19:45:49
【问题描述】:
我必须对 Ctypes 及其定义结构的方式提出具体问题。为了给你一点上下文,请考虑以下 C 中的示例,它定义了一个带有 bitfields 的结构:
#include <stdint.h>
#include <stdio.h>
struct Version
{
uint8_t n1;
uint8_t n2;
uint32_t n3:16;
} vv;
int main(void)
{
vv.n1 = 0xab;
vv.n2 = 0xef;
vv.n3 = 0x1234;
uint8_t* ptr = (uint8_t*)(&vv);
printf("size %u\n", sizeof(vv));
for (int i = 0; i < sizeof(vv); ++i) printf("%2x ", ptr[i]);
printf("\n");
return 0;
}
这似乎为 32 和 64 架构生成了相同的定义:
$ gcc sample.c -o a -m64 -std=gnu99 -w && ./a
size 4
ab ef 34 12
$ gcc sample.c -o a -m32 -std=gnu99 -w && ./a
size 4
ab ef 34 12
在那之前一切都很好,但是当我使用 ctypes 在 python 中编写等效结构时,我得到了不同的定义:
from ctypes import *
class Version(Structure):
_fields_ = [
('n1', c_uint8, 8),
('n2', c_uint8, 8),
('n3', c_uint32, 16),
]
vv = Version()
vv.n1 = 0xab
vv.n2 = 0xef
vv.n3 = 0x1234
print('bytes', bytes(vv).hex())
print('size', sizeof(vv))
因为 ctypes 结构使用 5 个字节而不是 4 个字节(这是 C 选择的那个)
$ python sample.py
bytes abef341200
size 5
如果我将python中n3的类型从c_uint32更改为c_uint16,它似乎与用C编写的代码具有相同的布局:
class Version(Structure):
_fields_ = [
('n1', c_uint8, 8),
('n2', c_uint8, 8),
('n3', c_uint16, 16),
]
...
$ python sample.py
bytes abef3412
size 4
如果我将所有内容更改为c_uint32,我会得到相同的结果:
class Version(Structure):
_fields_ = [
('n1', c_uint32, 8),
('n2', c_uint32, 8),
('n3', c_uint32, 16),
]
...
$ python sample.py
bytes abef3412
size 4
问题
- 如果 Ctypes 原生使用 c 库,为什么我会得到不同的结果?
- 为什么在第一个 python sn-p 中我得到一个额外的字节?我可以理解它是否是 4 的倍数,但为什么是 5 个字节?
- 为什么 python 中结构定义的最后两个版本似乎与 C 的功能兼容?
更新
我打开了一个问题https://bugs.python.org/issue41932,因为看起来这是一个错误,将继续更新这篇文章。
【问题讨论】:
-
这个问题似乎与github.com/python/cpython/pull/19850 有关,但没有编译指示。我也会尝试在那里跟进。
标签: python c ctypes bit-fields