Is it possible to emulate object methods in C? I’d like to be able self-reference a structure as a parameter to a member function argument e.g.:
struct foo {
int a;
int (*save)(struct foo *);
};
int
save_foo(struct foo *bar) {
// do stuff.
}
struct foo *
create_foo() {
struct foo *bar = malloc(sizeof(struct foo));
bar->save = save_foo;
return bar;
}
int
main() {
struct foo *bar = create_foo();
bar->a = 10;
bar->save();
}
Where, bar->save(), actually calls save_foo(bar). Seems like a long shot, but it’d be pretty slick 🙂
No, this is not possible. There are object-oriented libraries in C, but they pass the “
this” object to the “method” explicitly as inSee the Berkeley DB C API for an example of this style, but do consider using C++ or Objective-C if you want to do OO in a C-like language.