1

How do I initialize a fixed-size character array, such as char a[32], field of a structure using ctypes? Example:

import ctypes

class MyStructure(ctypes.Structure):
    _fields_ = [("a", ctypes.c_char * 32)]

a = (ctypes.c_char * 32)(*b"Hi!")
mystruct = MyStructure(a=a)

This gives me an error:

Traceback (most recent call last):
  File "...", line ..., in <module>
    mystruct = MyStructure(a=a)
TypeError: expected bytes, c_char_Array_32 found

Additional info: this is a MWE of a C++ DLL that has a structure with fixed-size character arrays that act as strings (e.g., names of things).

1 Answer 1

2

Pass a byte string as the error message suggests. ctypes will complain if it is too long:

import ctypes

class MyStructure(ctypes.Structure):
    _fields_ = [("a", ctypes.c_char * 32)]

mystruct = MyStructure(b'Hi')
print(mystruct.a)
mystruct = MyStructure(b'Hi'*16)
print(mystruct.a)
mystruct = MyStructure(b'Hi'*17)
print(mystruct.a)

Result:

b'Hi'
b'HiHiHiHiHiHiHiHiHiHiHiHiHiHiHiHi'
Traceback (most recent call last):
  File "D:\dev\Python36\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", line 326, in RunScript
    exec(codeObject, __main__.__dict__)
  File "C:\Users\metolone\Desktop\x.py", line 10, in <module>
    mystruct = MyStructure(b'Hi'*17)
ValueError: bytes too long (34, maximum length 32)
Sign up to request clarification or add additional context in comments.

2 Comments

Funny... I thought I had to initialize variables with their respective ctypes or ctypes.wintypes constructors. For example, there's a ctypes.int field, and it works if I either initialize it as b = 123 or b = ctypes.int(123).
Since type is declared in the structure (or .argtypes, for functions) Python knows the type and constructs it for you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.