You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
If python assume the size of 'c_int' 4, then it should return 12 in the first run. Also if it assume the size of 'c_int' 8 then it should return 24 in the second run.
This has to do with C struct packing and alignment. You are likely on a 64-bit computer and thus your structs are aligned to 8 byte (64 bit) boundaries.
I noticed this issue while working with 'mmap' and memory sharing.
As you said I check it in 'C++' and I got the same result for my struct as Python.
---------------------------------------------------------------------
I used the 'sizeof' function to calculate my struct size to read it from mapped memory and I get wrong output in reading memory because of this aligning procedure.
Question: Structs map to memory unaligned but sizeof return the aligned size of struct.
How we can calculate the sizeof struct to use it in reading from memory?
Activity
amiraslanhaghrah commentedon Dec 22, 2018
If you define a structure which contains an 'c_int' and a 'c_double' member. Then run the sizeof() function for it you get 16 as result as follows:
---------------------------------------------
output:
16
---------------------------------------------
In continue if you add another 'c_int' to your structure and run sizeof() function as follows. It return 16 too.
---------------------------------------------
output:
16
---------------------------------------------
If python assume the size of 'c_int' 4, then it should return 12 in the first run. Also if it assume the size of 'c_int' 8 then it should return 24 in the second run.
thanks in advance.
ammaraskar commentedon Dec 22, 2018
This has to do with C struct packing and alignment. You are likely on a 64-bit computer and thus your structs are aligned to 8 byte (64 bit) boundaries.
https://docs.python.org/2/library/ctypes.html#structure-union-alignment-and-byte-order
Create an equivalent C program and you will notice the same behavior.
amiraslanhaghrah commentedon Dec 22, 2018
Thank you for your response.
I noticed this issue while working with 'mmap' and memory sharing.
As you said I check it in 'C++' and I got the same result for my struct as Python.
---------------------------------------------------------------------
I used the 'sizeof' function to calculate my struct size to read it from mapped memory and I get wrong output in reading memory because of this aligning procedure.
Question: Structs map to memory unaligned but sizeof return the aligned size of struct.
How we can calculate the sizeof struct to use it in reading from memory?
ammaraskar commentedon Dec 22, 2018
Iterating over _fields_ and adding up the sizeof() for each type could be one solution.