Python Failed to read a structure containing a char array using Python's ctypes

Viewed 864

I wrote a tiny dll in C ,this is my .c file .

struct my_struct
{
    char arr[3];
};
__declspec(dllexport) struct my_struct func()
{
    struct my_struct m;
    m.arr[0] = 1;
    m.arr[1] = 2;
    m.arr[2] = 3;
    return m;
};
//compiled to testdll.dll

I tried to call the exported c function using python .This is my .py file.

from ctypes import *


class MyStruct(Structure):
    _fields_ = [("arr", c_char * 3)]


f = cdll.testdll.func
f.restype = MyStruct

for i in f().arr:
    print(i)

When I tried to read the array in the returned c struct ,I always got random values .

But if I use int arrays instead of char arrays in the .cpp and the .py files ,I can get right values as expected . Why?

Error when using ctypes module to acess a DLL written in C Related question here,I guess I should not return structs by value here ,because how structs are returned is implementation defined.

2 Answers
Related