The short answer is no. You would need C++ for that.
C function calls inside struct without using the same object
-
10-10-2022 - |
Question
For example, I have the C code below:
#include <stdio.h>
#include <stdlib.h>
struct a
{
void(*fun)(struct a *);
int x;
};
void fun(struct a *st)
{
++st->x;
}
struct a *new_a()
{
struct a *v = (struct a*)malloc(sizeof(struct a));
v->fun = fun;
return v;
};
int main()
{
struct a *v = new_a();
v->x = 5;
v->fun(v);
printf("%d\n", v->x);
}
This prints, of course, 6
, however, is there a way of not making the function call dependent of using the same struct to call it: v->fun();
, rather than v->fun(v);
?
Solution
OTHER TIPS
No. In C there is no easy way to do this. C++ provides this feature, it's called methods. If you are going to implement your own C with classes, you'll run into a syntax nightmare, before giving up.
A good C-style approach to object-functions will be the convention for functions taking one (mostly the first) parameter as a "self" (which is the reference to the object that gets managed).
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow