Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to simulate object/instance methods in C?

Tags:

c

oop

I'm aware that, because C isn't object oriented, the closest we can get to methods is using function pointers in a struct. This is just a thought exercise, but is it possible to have:

list.add(void* data)

without passing in the list itself as a parameter?

I know that:

list.add(list_t* list, void* data)

would be easy to implement, but is there any way, using whatever parts of C, to simulate a method in this way?

I recognize it's possible the answer is no, but please explain to me if you can! Thanks.

like image 813
Migwell Avatar asked Jan 14 '23 01:01

Migwell


2 Answers

This is the prettiest syntax I got using variadic macros (C99):

#define call(obj, method, ...) ((obj).method(&(obj), __VA_ARGS__))

usage (click for ideone):

struct class {
    int a;
    int (*method)(struct class* this, int b, int c);
};

int code(struct class* this, int b, int c) {
    return this->a*b+c;
}

struct class constructor(int a) {
    struct class result = {a, code};
    return result;
}

#define call(obj, method, ...) ((obj).method(&(obj), __VA_ARGS__))

#include <stdio.h>
int main() {
    struct class obj = constructor(10);
    int result = call(obj, method, 2, 3);
    printf("%d\n", result);
    return 0;
}
like image 114
Kos Avatar answered Jan 15 '23 14:01

Kos


Not only instance methods, but you can even have CLOS-style generic methods with the right library. Laurent Deniau's COS library (also see paper: [link]) provides a full OO system you can just #include and start using immediately; the method syntax is no heavier than any other function call.

It's apparently fast, too; the author claims to have gained a performance edge on similar code expressed in Objective-C (I'll take the claim itself with a pinch of salt, but even if they're comparable that's impressive).

like image 22
Leushenko Avatar answered Jan 15 '23 16:01

Leushenko