#define your way through the problem ...
As pointed out by previous authors, there is no automatic way to do what you ask, which, unfortunately, is obvious, since C has no way to make true OOP.
But a programmer can always crack himself through any obstacle. At the end of this post, I wrote you a sample hack to get around the problem.
There are ways to clean up the provided macro, although it will not be so portable.
- implementation of C99
#include <stdio.h> #include <stdlib.h>
...
#define SCOPIFY(TYPE,NAME, ...) { \ ctor_ ## TYPE(& NAME); \ __VA_ARGS__ \ dtor_ ## TYPE(& NAME); \ } (void)0
...
typedef struct { int * p; } Obj; void ctor_Obj (Obj* this) { this->p = malloc (sizeof (int)); *this->p = 123; fprintf (stderr, "Obj::ctor, (this -> %p)\n", (void*)this); } void dtor_Obj (Obj* this) { free (this->p); fprintf (stderr, "Obj::dtor, (this -> %p)\n", (void*)this); }
...
int main (int argc, char *argv[]) { Obj o1, o2; SCOPIFY (Obj, o1, fprintf (stderr, " o1.p -> %d\n", *o1.p); SCOPIFY (Obj, o2, int a, b; fprintf (stderr, " o2.p -> %d\n", *o2.p); (*o1.p) += (*o2.p); ); fprintf (stderr, " o1.p -> %d\n", *o1.p); ); return 0; }
output ( http://ideone.com/WYrjU )
Obj::ctor, (this -> 0xbf8f05ac) o1.p -> 123 Obj::ctor, (this -> 0xbf8f05a8) o2.p -> 123 Obj::dtor, (this -> 0xbf8f05a8) o1.p -> 246 Obj::dtor, (this -> 0xbf8f05ac)