Skip to main content
gamedev.net
🔒 Locked

MSVC - packed structs

Started by uNiQue0815 2 replies 5.3k views
Original Post
uNiQue0815
uNiQue0815
i want to write a macro to make struct/class packed. should be something like : PACKED(class myClass) { char aCharMember; short aShortMember; int anIntMember; }; for example on g++, the PACKED-macro would expand to class myClass __attribute((packed)) ... but what would it have to expand to on MSVC ? i tried : __declspec(align(1)) class myClass ... -> seems not to work -> it only lets me set higher values than are defined by #pragma pack, or compiler options. lower values (like 1) are ignored. is there some other way ? or is it somehow possible, to get the #pragma pack-directive into the PACKED-macro ? any ideas ?
Endurion
Endurion
In MSVC it''s

#pragma pack(1) (or (2) or whatever)

and

#pragma pack() for setting back to the default
Fruny: Ftagn! Ia! Ia! std::time_put_byname! Mglui naflftagn std::codecvt eY'ha-nthlei!,char,mbstate_t>
Aprosenf
Aprosenf
To be more specific, what you want to do is:
#pragma pack(push, 1);

class myClass
{
...
};

#pragma pack(pop)


MSVC keeps a stack of the packing state, so after it leaves your header file, the push and then pop will leave the packing state in the same state as it was in before it got to your header file in the current translation unit. Unfortunately, you cannot have a #pragma as the definition of a token, so you''ll either need to add those lines yourself or put them in another header file that is included.
uNiQue0815
uNiQue0815
mmkay... trying to be more specific:

of course i know about ''#pragma pack'' with all its pushs & pops... that''s the way i did it before and still do it now...

i want do define one single macro for each platform/compiler, to pack the structures, so i can compile on different compilers without having to change the code...

i don''t want to have to write blocks of compiler directives before and after each of my struct-/class-declarations, with lots of
#if MS-COMPILER
...
#elseif GNU-COMPILER
...
#elseif [...]
...
#endif

just wanted to do all this by macro... something like :

PACKED(class myClass)
{
char aCharMember;
short aShortMember;
int anIntMember;
};

on G++ it''s no problem, but on MSVC i haven''t found a solution, yet, because i can''t put ''#pragma pack'' into a macro, and __declspec(align(1)) seems not to work properly... (or maybe i just misunderstood its functionality ?!)


if there''s no other "good" solution, maybe i''ll do it like you told me, Aprosenf, ... create two headers "pack.h" and "unpack.h", which are included before and after the struct-/class-definition... :D ... but that wouldn''t be very stylish, would it ? :D

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.