gcc 4.4.1 c89
I have 2 different structures called origin_t and session_t.
I would to pass the instance of one of these structure to my function. However, before I can perform an operation on these I need to cast it to the correct type. My problem is that I don’t know how to check for the correct type. Is there any standard c function that can check for the correct instance of this structure.
Many thanks for any advice,
const char* get_value(void *obj)
{
/* Cast to the correct structure type */
if(obj == origin) {
/* Is a origin structure */
origin_t *origin = (origin_t*)obj;
}
else if(obj == session) {
/* Is a session structure */
session_t *session = (session_t*)obj;
}
}
The best way would be to combine the types (if possible!) under a common type such as:
and then:
There are no ways of determining types from a pointer in C. You have to add your own type mechanism. This is one way to do it without being intrusive in the subtypes (origin_t and session_t). You also don’t have to do weird casts, and compromise the already weak type system in the C language.