Reputation: 1125
How do I figure out the type of an object in C? My goal with this is to create a linked-list container in C.
Let's assume I have a function that takes a void pointer:
...
Foo *f;
f = Allocate(f);
...
void *Allocate(void *item)
{
return malloc(sizeof(f.GetType));
}
How do I make the above syntax possible?
Upvotes: 0
Views: 113
Reputation: 151
void *Allocate(void *item)
{
return malloc(sizeof(f.GetType));
}
It is impossible. ISO C language does't supply any facility to get the type info through variable. Gcc's extensions contains an operator called 'typeof', it could get the type info from a real type. such as:
typeof (x[0](1))
int a; typeof (a) b; b = a;
but even though typeof also could not get the real type info from a void pointer. the code below could not be compiled succesfully:
void *Allocate(typeof(*item) *item)
{
return malloc(sizeof(*item));
}
Upvotes: 1
Reputation: 72805
The (arguable) beauty of C is that it doesn't do this. A void pointer is just an address that could point to anything. You could either create your own object system (structures with a "type" field and a "data" field is a simple way). From your implementation, it might also be possible to stick an allocate
function into the Foo
structure (assuming that it is) which knows how to allocate itself (the type is known here).
Upvotes: 1
Reputation: 36102
The only way to do this in C is to create your own type system where you include typeinfo to the types that you create. That is what has been done for instance in Objective-C. In C, all types are just a series of bytes, when you allocate memory you are allocating just bytes, what you use those bytes for is of no concern to the C compiler.
Upvotes: 1
Reputation: 16617
It is just not possible to get the type
using a void *
to that object. If you can calculate the size of Foo
before calling Allocate()
, then get the size and pass it as a parameter to Allocate()
, else you should make Foo
visible inside Allocate()
to find the size.
Upvotes: 1
Reputation: 181017
In C, there's no cross platform way to find out the underlying type of a void*, since the type information is not stored in the object. In C++ this feature has been added for objects.
You could of course implement it yourself for your own objects by - for example - storing the size of every object in the object itself, but for system objects there is no built in way.
Upvotes: 2
Reputation: 5469
That's not possible. A void *
pointer, is just a pointer to the memory, nothing more, no more information is attached to it. It's impossible to do what you are asking, you can't know how many bytes to malloc
.
That's why, the qsort
function from stdlib.h
library takes as a parameter
the size
in bytes of each array element. If what you suggested was possible, then
qsort
wouldn't need such a parameter.
Perhaps you could do something like this:
...
Foo *f;
f = Allocate(f, sizeof(Foo));
...
void *Allocate(void *item, size_t size)
{
return malloc(size);
}
Upvotes: 2