I have a quite strange and exotic question. My goal is to program object oriented in C. For this, a common approach is to define function pointers inside a struct and define as first argument an explicit reference to the calling struct:
struct Point {
int x;
int y;
int (*sum)(struct Point* p);
};
int sum(struct Point* p) {
return p->x + p->y;
}
int main() {
struct Point p;
p.sum = ∑
p.sum(&p);
}
However, I was wondering if it is possible to do this without the additional struct Point*
argument.
For this I need to manipulate the stack (probably via inline assembly) to have a reference to p
which then can be accessed inside sum
.
My current idea is to declare an additional local variable right before the function call, which holds a reference to the struct
void* ptr = &p;
and then push this value onto the stack with
__asm__("push %rax\n");
But I couldn't figure out how I can access my pushed value in the sum function. I use GCC on x86.