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

I know that since C is not object oriented, the closest we can get to methods is to use function pointers in a structure. This is just a mental exercise, but is it possible:

list.add(void* data) 

without going to the list as a parameter?

I know that:

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

it would be easy to implement, but is it possible to use in any way any parts of C to mimic the method in this way?

I admit that the answer is no, but please explain to me if you can! Thanks.

+4
source share
4 answers

This is the cutest syntax I've used with variable 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; } 
+6
source

Not only instance methods, but you can even use common CLOS methods in the right library. COS library Laurent Deniau (also see article: [link] ) provides a complete OO system, you can simply #include and start using immediately; method syntax is no heavier than any other function call.

This is obviously fast too; the author claims that he gained an advantage over the same code as in Objective-C (I myself will take the requirement with a lot of salt, but even if they are just as impressive). A.

+2
source

To emulate OO method calls, you need objects with class or vtable pointers. If your list_t contains, say, a funcs element that points to a structure containing pointers to functions, one of which is add , then your use will be

 list->funcs->add(list, data) 

which you could capture in a variable macro:

 #define OO(obj, func, ...) (obj)->funcs->func(obj, __VA_ARGS__) OO(list, add, data); 
+1
source

If you need something simple, you can implement struct member functions using the block language extension. Blogged here .

You can use blocks to lambda capture a bound structure by simulating this pointer.

There is no virtual dispatch with this approach, so it's up to you whether you think these are true objects.

0
source

Source: https://habr.com/ru/post/1488445/


All Articles