Hamza Yerlikaya
Hamza Yerlikaya

Reputation: 49329

GCC Determine type of void* at runtime

I am working on a generic container where data is held using a void*, I know that there is no way to determine the type of void* at runtime in C. What I was wondering is that is it possible to do it using a gcc extension or any other trick? I only need to determine between my type and any other type, one function of mine needs to determine if it is passed a container of mine or any other type if it is a container do something else do nothing.

Upvotes: 0

Views: 543

Answers (3)

Jim Balter
Jim Balter

Reputation: 16406

One way is to put all instances of your data type in a hash table and do a lookup to see if the arg is in the table. Another way is to allocate all instances of your data type from a contiguous area of memory and check the arg to see if it's in that area -- early LISP interpreters worked that way. Otherwise, pass a flag to the routine, or call two different routines.

Upvotes: 1

datenwolf
datenwolf

Reputation: 162164

You could implement a custom RTTI system, like:

typedef struct t_record {
    enum { type_A, type_B } type;
    union {
        struct {
            int foo;
            float bar;
        } A;
        struct {
            unsigned int n;
            char buf[128];
        } B;
    };
} record;

void eggs(int, float);
void salad(unsigned int n, char const * const);

void spam(record *r)
{
    if(r->type == type_A)
        eggs(r->A.foo, r->A.bar);

    if(r->type == type_B)
        salad(r->B.n, r->B.buf);
}

Upvotes: 2

nmichaels
nmichaels

Reputation: 50941

One way to handle this is with an additional argument to the function. Another is to encapsulate your void * in a struct that brings some type data along for the ride. The compiler most likely won't be able to help you here.

Upvotes: 4

Related Questions