ant2009
ant2009

Reputation: 22486

type checking structures

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;
    }
}

Upvotes: 2

Views: 163

Answers (3)

Jörgen Sigvardsson
Jörgen Sigvardsson

Reputation: 4887

The best way would be to combine the types (if possible!) under a common type such as:

typedef enum {
    t_origin,
    t_session
} type_t;

struct base_t {
    type_t type;
    union {
        origin_t origin;
        session_t session;
    };
}

and then:

const char* get_value(base_t *obj)
{
    /* Cast to the correct structure type */    
    if(obj->type == t_origin) {
        /* Is a origin structure */
        origin_t *origin = &obj->origin;
    } 
    else if(obj->type == t_session) {
        /* Is a session structure */
        session_t *session = &obj->session;
    }
}

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.

Upvotes: 3

StasM
StasM

Reputation: 11002

C doesn't have any built-in runtime type information capabilities, so you'd have to create your own - for example, by putting at the beginning of both origin_t and session_t some integer or pointer to some data structure that would allow you to distinguish between them.

Upvotes: 4

Jonathan Wood
Jonathan Wood

Reputation: 67193

Is there any way to modify the types? Seems like the easiest way it to put a small member that indicates the type if there's no other way to tell.

Upvotes: 4

Related Questions