1

Right now, I am writing a small project in C to test out some serialization techniques. One way that I am doing this is through the use of unions. Something that I would like to try is creating a union in the C preprocessor that holds a user-defined structure. For example, something like this:

#define create_union(name_of_structure, type_of_structure) \ 
                                                           \
typedef union name_of_structure {                          \                                 
      typeof(type_of_structure) structure;                 \                        
      char buffer_that_holds_structure[sizeof(type_of_structure)]; \
} name_of_structure;

/* Usage */
struct my_data {
      int id;
      int other_value;
};

create_union(my_data_t, struct my_data);
/* Data type my_data_t (union my_data_t) now exists */

First of all, is this feasible? If it is, how would I go about doing this? If not, is there an alternative method I can use?

Thanks!

2
  • 1
    typeof(type_of_structure) -> type_of_structure? Also, have you compiled this? Was there an error? If not, did you check with -pedantic -Wall flags to be sure? Commented Feb 27, 2018 at 23:05
  • It compiles with -Wall and -pedantic. The typeof() is unnecessary. Commented Feb 28, 2018 at 21:35

1 Answer 1

2

Yes, it's possible, and your code is very close to correct.

I'd drop the semicolon at the end of the macro definition. I'd also drop the use of typeof; it's not portable and it's not needed unless you want to use an expression, rather than a type name, as the first argument to create_union.

Here's how I'd probably define it. (I don't bother with typedefs for struct or union types; I just use the name struct foo or union foo unless the type is intended to be completely opaque. Feel free to use the typedef if you prefer.) (I've also used unsigned char rather than char, since that's how object representations are defined.)

#define CREATE_UNION(new_type, existing_type) \
union new_type {                              \
      existing_type obj;                      \
      unsigned char rep[sizeof(existing_type)]; \
}

And you can then do:

CREATE_UNION(int_wrapper, int);
int_wrapper foo;

Note that what you're defining is a union, not a structure.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.