Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling
 
PerlMonks  

Re^9: Perl XS binding to a struct with an array of chars*

by Marshall (Canon)
on Nov 28, 2022 at 07:31 UTC ( #11148420=note: print w/replies, xml ) Need Help??


in reply to Re^8: Perl XS binding to a struct with an array of chars*
in thread Perl XS binding to a struct with an array of chars*

I was surprised to learn that size of int is 32 bits even on a 64 bit compiler. But that is true. To get 64 bit int, even long long is required on some compilers.

What I found out is that default for the 64 bit gcc compiler is to enable padding to maintain dword memory alignment in structures. This is what is causing the seemingly weird results with your sizeof() test code. sizeof() can return more than the obvious number of bytes due to padding. See Data Alignment in Structs for some more info. There is a way in gcc to override this behavior if perhaps you need to match some weird binary structure exactly verbatim. Just like malloc(), struct address assignment "likes" dword (64 bit alignment).

typedef struct _foo { int count; //with just int, sizeof() is 4 bytes char anything; //forces sizeof() increase from 4 to 8 bytes! } foo;
Evidently, even putting something in the struct that has no storage, like char* pointer[], forces alignment bytes to be added. The mysterious extra 4 bytes aren't anything, they are just junk padding bytes. The pointer(s) when added will be 8 bytes and it is highly desirable for these to be fully contained on a single memory row. If they are on 32 bit boundaries, the hardware can still read them, but at a performance penalty.

So my code as written performs correctly, however the explanation of why the struct is 8 bytes is not correct. 4 bytes are for the integer (not 8 as I wrongly assumed) but then an additional 4 bytes are added as padding. 4+4=8. So the entire array of pointer is 64 bit aligned (8 byte boundary).

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11148420]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others avoiding work at the Monastery: (5)
As of 2023-02-07 11:19 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    I prefer not to run the latest version of Perl because:







    Results (39 votes). Check out past polls.

    Notices?