[issue45285] c_char incorrectly treated as bytes in Structure

CireSnave report at bugs.python.org
Sat Sep 25 14:53:23 EDT 2021


CireSnave <ciresnave at yahoo.com> added the comment:

Wow.  Thank you Eryk Sun.  While that seems like a convoluted way to make a type act like the type it is...it works.  Verified it with the following code:

from ctypes import POINTER, c_char, sizeof, Structure


class char_from_c(c_char):
    pass


print("Size of c_char vs size of char_from_c:")
print(sizeof(c_char))
print(sizeof(char_from_c))


class my_structure(Structure):
    _fields_ = [
        ("first_char", char_from_c),
        ("second_char", char_from_c),
        ("third_char", char_from_c),
    ]


my_structure_object: my_structure = my_structure(97, 98, 99)

pointer_to_char_from_c_in_my_structure = POINTER(c_char)(my_structure_object.first_char)

print("\nContents of pointer_to_char_from_c_in_my_structure:")
print(pointer_to_char_from_c_in_my_structure.contents)
print("\npointer_to_char_from_c_in_my_Structure[0]:")
print(pointer_to_char_from_c_in_my_structure[0])

print("\nValues from my_structure_object:")
character_counter = 0
while character_counter < sizeof(my_structure_object):
    print(pointer_to_char_from_c_in_my_structure[character_counter])
    character_counter += 1



...which gave me the following results:

Size of c_char vs size of char_from_c:
1
1

Contents of pointer_to_char_from_c_in_my_structure:
c_char(b'a')

pointer_to_char_from_c_in_my_Structure[0]:
b'a'

Values from my_structure_object:
b'a'
b'b'
b'c'


Again...Thank you.  Closing this "bug" as it is weird...but not a bug.

----------
resolution:  -> not a bug
stage:  -> resolved
status: open -> closed

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue45285>
_______________________________________


More information about the Python-bugs-list mailing list