【问题标题】:ctypes: are bit fields supported for c_uint8?ctypes:c_uint8 是否支持位字段?
【发布时间】:2018-07-20 13:38:23
【问题描述】:

我在玩一些 ctype 结构,发现了一些有趣的东西,让我对我的实现感到疑惑。 MWE如下:

from ctypes import *
import numpy as np

class test_bitfield(Structure):
    _fields_ = [("x", c_uint16, 9),
                ("y", c_uint8, 5),
                ("z", c_uint16, 4)]

bf = test_bitfield(np.uint64(9), np.uint64(9), np.uint64(9))

print(bf.x, ", ", bf.y, ", ", bf.z)

谁的输出是:

9, 0 ,9

这出乎我的意料。

通过将bf.y 转换为c_uint16,我得到了我从一开始就期望得到的结果:9, 9, 9

看了一眼文档,我看到bitfields are only possible for integer fields,它并没有真正指定不支持c_uint8。然后我参考了可用的tests,我发现其中没有包含c_uint8c_char。但是,尝试使用 c_char 会引发 TypeError,而 c_uint8 不会引发。

有人可以澄清发生了什么吗? uint_8 没有实现位字段吗?还是我只是用错了?任何类型的澄清都非常感谢!

提前致谢!

【问题讨论】:

  • c_uint8 应该是一个整数字段,这是什么版本的python,在什么架构上运行......以及什么解释器(可能对FFI的东西很重要)
  • 好吧..我猜它没有

标签: python ctypes bit-fields


【解决方案1】:

注意:Mac OS X python 2.7 和 3.6 具有相同的输出

所以...由于某种原因,您不能使用带符号或无符号的 8 位类型并用位域划分它们...我将查看文档以了解“为什么”

from ctypes import *

class test_bitfield(Structure):
    _fields_ = [("x", c_uint16, 9),
                ("y", c_uint16, 6),
                ("z", c_uint16, 4)]

bf = test_bitfield(1,255,3)

print(bf.x, ", ", bf.y, ", ", bf.z)

输出:(1, ', ', 63, ', ', 3) 这很酷,去掉了 2 个最高位:255 - 128 - 64 = 63

from ctypes import *

class test_bitfield(Structure):
    _fields_ = [("x", c_uint16, 9),
                ("y", c_uint8, 8),
                ("z", c_uint16, 4)]

bf = test_bitfield(1,255,3)

print(bf.x, ", ", bf.y, ", ", bf.z)

打印:(1, ', ', 255, ', ', 3) 好的...理智

但是,

from ctypes import *

class test_bitfield(Structure):
    _fields_ = [("x", c_uint16, 9),
                ("y", c_uint8, 7),
                ("z", c_uint16, 4)]

bf = test_bitfield(1,255,3)

print(bf.x, ", ", bf.y, ", ", bf.z)

打印:(1, ', ', 0, ', ', 3)

【讨论】:

  • 感谢您的分析。这对我来说仍然很困惑,因为通过修改我的示例以从结构和打印中取出“x”,并让其他所有内容保持不变,它实际上输出9, 9,正如我所期望的那样。就好像邻居内存和数据类型也影响位字段,这会告诉它正在做某事(意味着它被支持(?)),虽然我还不知道它在做什么。跨度>
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-17
  • 1970-01-01
相关资源
最近更新 更多