ctypes Structure Type Inconsistency

Viewed 26

There's an inconsistency in ctypes when using structure members versus basic types. The basic types have ctypes type definitions, while structure members get python type definitions. Oddly, I'm able to use assign the python-typed structure members and the values are stored properly in my foreign shared object. Here's my C code:

#include <stdio.h>

unsigned int myvar;

typedef struct
{
    unsigned int mymember;
} mystruct_t;

mystruct_t mystruct;

void print(void)
{
    printf("myvar=%u\r\n", myvar);
    printf("mystruct.mymember=%u\r\n", mystruct.mymember);
}

The python code:

import ctypes

class mystruct_t(ctypes.Structure):
    _fields_ = [('mymember', ctypes.c_uint)]

mylib = ctypes.CDLL("/path/to/mylib.so")

mylib.print()
print("")

myvar = ctypes.c_uint.in_dll(mylib, "myvar")
mystruct = mystruct_t.in_dll(mylib, "mystruct")

print(type(myvar))
print(type(mystruct.mymember))
print("")

myvar.value = 1
mystruct.mymember = 2

mylib.print()

And the output:

myvar=0
mystruct.mymember=0

<class 'ctypes.c_uint'>
<class 'int'>

myvar=1
mystruct.mymember=2

This isn't a major issue, but it's going to cost future developers some time when they run into this. Is there a way around it?

0 Answers
Related