cstructunions

Define variable as member of c union?


I am working on a large project which was written by someone else. There is a global general purpose buffer that is reused in many places of the project. I want to add some code that will use this buffer but I want to use a struct, typically I would use a union for this, i.e.

typedef union StructuredBuffer {
    MessageStructure message;
    uint8_t bytes[BUFFER_SIZE];
} StructuredBuffer;

StructuredBuffer structuredBuffer;

and access the struct with: structuredlBuffer.message.structMember ...

and the raw buffer with: structuredBuffer.bytes ...

The issue I have is that generalBuffer is already used in lots of different places and I don't want to change all that code to use generalBuffer.bytes (instead of generalBuffer), is there a way I can change the definition of generalBuffer to "point" to structuredBuffer.bytes so that I can use the memory of general buffer as a union but the rest of the project can use it as it currently does?

(when I say "point" I know this is the wrong word as I don't want a pointer that needs to be dereferenced, but I'm not sure what else to call it)


Solution

  • Assuming your union is the right solution, I'd break the code and fix all the things that fail to compile. It's safe, relatively quick, the right thing to do and totally reliable that you've addressed all references. Do it on a Friday afternoon or sometime when you don't want to think too hard but have to be "working".

    If your IDE can do it for you then so much the better.