Reputation: 1778
If we have two types of structure say apple and orange with their instances as a1 and o1, then we have a pointer to of type void then is there a way of knowing what type of structure it points to?...
Upvotes: 2
Views: 133
Reputation: 234665
No you can't do this natively in C.
One solution would be to stub malloc()
for the types you're interested in and maintain a table of pointers as keys and object types as values. Read that table when you need to know the type.
Don't forget to make similar stubs for calloc()
and free()
.
Upvotes: 2
Reputation: 5773
One way to check the type of a structure is to use magic values.
struct <your_struct> {
uint32 magic;
// rest of your struct
}
You could then check if the magic values match during runtime with something like
assert(<your_struct>->magic == STRUCT_MAGIC_CONSTANT);
Upvotes: 2
Reputation: 6532
Not without a great deal of hacking. If you have control of the source code, you could conceivably place this information into the structures:
typedef enum {
STRUCT_TYPE_APPLE,
STRUCT_TYPE_ORANGE
} _struct_type;
typedef struct {
_struct_type type;
/* Your "apple" data */
} apple;
typedef struct {
_struct_type type;
/* Your "orange" data */
} orange;
You can then cast to an appropriate type during debugging and check the value of type
. Naturally, this is riddled with brittleness. Notably, if you aren't sure what type of structure you're going to be getting, casting and checking type
could well get you something with the same value of STRUCT_TYPE_APPLE
or STRUCT_TYPE_ORANGE
.
Upvotes: 5
Reputation: 15861
C does not maintain this sort of information at runtime. So you're out of luck, I'm afraid.
Upvotes: 5