Re: struct data offsets
- From: Stephen Sprunk <stephen@xxxxxxxxxx>
- Date: Thu, 29 Jan 2009 15:19:28 -0600
g3rc4n@xxxxxxxxx wrote:
i was playing around with the idea of getting some sort of virtual
function functionality out of c when playing about with pointers and i
was trying to do something like this
void say_hi();
struct foo{
unsigned offset;
int something;
double somethingelse;
void (*fun)();
};
struct bar{
unsigned function_offset;
void(*the_function)();
};
void init(struct foo* arg){
arg->offset = foo::fun;
foo::fun is a syntax error in C.
arg->fun = say_hi;
}
void init(struct bar* arg){
You cannot have two different functions with the same name in C.
arg->function_offset = bar::the_function;
bar::the_function is a syntax error in C.
arg->the_function = say_hi;>
}
void fun(void* arg){
arg += (void*)(unsigned*)arg; // i know this doesn't work
If you know it doesn't work, at least try to explain what you're trying to do, since incrementing one void pointer by another void pointer is completely nonsensical.
((void(*)())arg)();
That makes my brain hurt. Function pointers are a very, very good reason to use typedefs.
}
int main(){
struct foo f;
init(&f);
fun(&f);
struct bar b;
init(&b);
fun(&b);
return 0;
}
so can you just read the offset of a structs data then mainpulate the
void* and do something with it?
What void*? The only (void *)s in your code is the argument to fun().
Here's what I think you're trying to do:
typedef void (*fptr)();
void foo_say_hi();
void bar_say_hi();
struct foo {
fptr fun;
};
void foo_init(struct foo *arg){
arg->fun = foo_say_hi; /* set base method in vtable */
}
struct foo {
fptr fun; /* copy all elements of parent struct at beginning */
int something; /* new elements in child struct */
double somethingelse;
};
void bar_init(struct bar *arg){
foo_init(arg); /* always chain to parent's constructor */
arg->fun = bar_say_hi; /* override base method in vtable */
}
int main(){
struct foo f;
foo_init(&f); /* call constructor */
f.fun(); /* calls foo_say_hi() */
struct bar b;
bar_init(&b); /* call constructor */
b.fun(); /* calls bar_say_hi() */
return 0;
}
--
Stephen Sprunk "Stupid people surround themselves with smart
CCIE #3723 people. Smart people surround themselves with
K5SSS smart people who disagree with them." --Isaac Jaffe
.
- Prev by Date: 'execl' query
- Next by Date: Re: 'execl' query
- Previous by thread: Re: struct data offsets
- Next by thread: Re: struct data offsets
- Index(es):
Relevant Pages
|