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.
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.
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);
}
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.
精彩评论