ctypes.Structure and bitfields

I have been using bit-fields with ctypes.Structure.

I have a bitfield struct, and my issue is that no matter what I do, I am unable to set the values for my fields.

A structure with the following definition:

from ctypes import Structure, c_byte, c_int
class Demo (Structure):
 _fields_ = [
  ('f1', c_byte, 8),
  ('f2', c_int, 21),
  ('f3', c_byte, 2),
  ('f4', c_byte, 1)
 ]

I have set the above struct using from_buffer_copy with a value of b'\x01\x0f\x00\xe0' (Binary representation of C struct, with the underneath values).

This should set the following values

  • f1: 1
  • f2: 15
  • f3: -1 (3, overflow makes it -1)
  • f4: -1 (1, overflow makes it -1)

Manual setting, or from_buffer_copy, achieve nothing; f3, and f4 remain 0.

Could someone help me set f3, and f4 to corresponding values (-1 in this example). Also how would I access these fields in bit form of their corresponding size.

Hi,
Hot take - maybe try with setting pack attribute to 1 for this class?

SO CTypes Bitfields can be used as nice reference, eventually This project

Setting _pack_ does not achieve any changes in the code.

You could check out SO ctypes.Structure and bit fields. Also this issue, now seems to provide an answer to the error.

This is an interpreter problem, because of a fault in the Python implementation for ctypes.Structure.

General tip: Don’t be too hasty to claim that something’s a bug. It just makes you look like a fool if you’re wrong.

In this case, I tweaked your code like this:

from ctypes import Structure, c_int
class Demo(Structure):
	_fields_ = [
		('f1', c_int, 8),
		('f2', c_int, 21),
		('f3', c_int, 2),
		('f4', c_int, 1),
	]

d = Demo.from_buffer_copy(b'\x01\x0f\x00\xe0')
print(d.f1, d.f2, d.f3, d.f4)

and I got values of 1, 15, -1, and -1. The only difference is that I looked at the documentation, rather than going to a toxic Q&A site.

and then used the c_int type as is documented.

1 Like

So it seems that we still need to find a way to get bitfields working right. I also don’t assume bug in core python module, so we’re on the same page here.
I will try to search my resources in order to find bitfield related ctypes structures to show, because we deal with vxlapi.dll :slight_smile:

Okay, I found something.
ctypes-bitfield uses pack attribute and few other things to achieve bitfields with ctypes. Plus, here’s more sophisticated usage of ctypes, for Windows: pyWinAPI. I hope that helps! :slight_smile: