3

I can't seem to find any information on how to calculate padding within a struct or a class within C, C++.

In HLSL there are data structures called "Constant Variables" and they are very much like C structs with #pragma pack (4) enabled. Here is a link for more information with regards to Constant Variables in HLSL.

The problem I am having is with trying to create a struct format descriptor. After parsing the HLSL code, a constant descriptor will contain information about the data types contained within a constant variable struct. It will describe the data type of each member variable, its offset and the total size of the struct. The trouble I am having is in determining the final size of a struct due to padding.

If there is an algorithm for this then I should be able to code it up and calculate the actual padded size of any "Constant Variable" in HLSL. The problem is I don't know what it is and nor do I know where to find it?

Nicolas Kaiser
  • 1,628
  • 2
  • 14
  • 26
Sent1nel
  • 509
  • 1
  • 7
  • 21
  • It is not clear what you want to do. You say you want to know "the actual padded size", then what is wrong with `sizeof`? – Oliver Charlesworth Jun 21 '11 at 23:23
  • Are you trying to do this at runtime or compile-time? Or are you trying to make a tool that processes HLSL and generates C/C++ objects that have the proper padding for HLSL constants? – Nicol Bolas Jun 21 '11 at 23:31
  • Why don't you just use the compiler to help you figure it out? Use the sizeof keyword, the offsetof() macro and whatever #pragma your compiler supports to change the packing. #pragma pack is supported by MSVC. – Hans Passant Jun 21 '11 at 23:36
  • This is a run time operation and its purpose is to determine how to map data between the CPU memory and the constant registers of the GPU. – Sent1nel Jun 22 '11 at 00:01
  • Those internal paddings are compiler/platform dependant and often not externally documented, at least not in corner cases. If you really need those paddings, your best bet is to generate C code for those structs and generate code that prints its internal layout, compile that code and parse the output. – nos Jun 22 '11 at 00:29

1 Answers1

1

My question is asking for the algorithim used to make #pragma pack 4 work. (e.g. does it look at one variable at a time within a struct and use some sort of max size test to determine where to pad or does it analyses the entire struct and somehow shuffle data around.)

The compiler cannot shuffle data around in a C-style struct. C guarantees that the members are allocated in exactly the order they are declared. Any padding must come between members or at the end of the struct.

A C++ class with access specifiers does not have to be compatible with C, so some reordering is allowed.

Bo Persson
  • 90,663
  • 31
  • 146
  • 203