coopassembly

emulating thiscall in C to achieve struct functions without self-referencing


This is relating to the flurry of object-oriented C postings, but differs in that I don't want all the features, just one:

An ability to do this:

struct foo { 
  int (*bar)(void);
  char baz;
};

An then have the back-reference. C has a calling convention called cdecl; basically pushes arguments on to the stack, has a return pointer, then jumps to some address. The code at that address pops arguments off the stack and goes on its merry way.

The thiscall convention is slightly different in that it adds one extra argument, a "this" pointer, implicitly.

Since you can start executing arbitrary byte code in C quite easily AND since gcc supports inline assembler templating, this sounds like you could just make some macro so that you could do something like:

int bar(void) {
  GETTHIS;
  cThis->baz = 0;
}

int createFoo(struct Foo*pFoo) {
  ASSIGN(pFoo, bar);
} 

Basically what ASSIGN would do is sidestep cdecl in someway to emulate a thiscall style convention and then what GETTHIS would do is the other side of the accounting trick.

I was wondering if:

Just this alone; the convenience of true "We're all consenting adults here" style member functions, would be simply awesome. Thanks!

Notes:


Solution

  • My friend eventually got it: https://gist.github.com/1516195 ... requires specifying function arity and is limited to x86_64 ... but yes, it's a pretty nice compromise that makes things really unobtrusive.