Luca wrote:
I have the following problem:
I'm developing a system where there are some processes that
communicate each other via message queues; the message one process can
send to another process is as follows:
******************************************
struct ST_MSG {
int iType;
char aData[MAX_DATA_PART_LENGTH];
}
******************************************
the message is composed of two parts: iType tells about the kind of
message and the aData buffer contains the informative part.
depending on the value assumed by iType, the aData buffer has to be
cast explicitely to the proper structure.
I hope you don't actually intend to cast it. That is unlikely to result
in correct, portable, well-defined code.
the problem I have is that of determining the value of
MAX_DATA_PART_LENGTH
I have tried using the #define macro of the preprocessor but, due to
the high number of structures, the compiler crashes.
Sounds like you need a better compiler. Anyway, you should use const
rather than #define for creating constants.
Your actual question doesn't make much sense. You can't create or use
instances of your structure without knowing the size. In the example
above, the size is MAX_DATA_PART_LENGTH. That should be sufficient for
determining the size. You could also use sizeof(msg.aData) where msg is
an instance of ST_MSG.
I wouldn't like to use an off-line solution such as building a
separate project whose only job is that of calculating the
MAX_DATA_PART_LENGTH number.
I would like to solve the problem during the compilation of my prject
Maybe I misunderstood the question at first. If you are asking what
value to give MAX_DATA_PART_LENGTH, then I think it depends heavily on
what you are doing with it. If you have structs representing each of the
possible message types, you could create a union of all of them:
union SizeUnion
{
StringMessage s;
LongMessage l;
//...
};
Then the maximum size required to store any of those structures is
sizeof(SizeUnion).
However, this is not necessarily a good solution. It relies on the
assumption that messages are no larger than the structures that are used
to represent them. This may be the case if you simply memcpy the data
from a struct into a char array and pass that along, but this is not a
very good solution to the problem - it is inflexible, confining,
non-portable (in the sense that structs may not be the same across
platforms or compilers), lends itself to errors (such as alignment
problems), difficult to extend, and sloppy.
The "correct" way to handle something like this is to define a protocol
for serializing your message types. That protocol would include details
about the sizes of the messages. This doesn't allow you to determine the
size at compile time, since the size is determined by the protocol. But
implemented correctly it is much easier to deal with, much more
flexible, and should give nice, clean results.
-Kevin