Hello, I am creating a special struct with unknown functions. I use this approach:
Callbacks.h
Code:
#ifndef CALLBACKS
#define CALLBACKS
struct Callbacks;
struct Callbacks* getNewCallback();
#endif // CALLBACKS
And implementing it that way:
Code:
#include "callbacks.h"
#include <stdlib.h>
#include <stdio.h>
typedef void (*doit)(void);
typedef void (*dont)(void);
struct Callbacks {
doit doers[1];
dont donters[1];
};
static inline void __do1(void) {
printf("Do it 1\n");
}
static inline void __do2(void) {
printf("Do it 2\n");
}
static inline void __do3(void) {
printf("Do it 3\n");
}
static inline void __do4(void) {
printf("Do it 4\n");
}
static inline void __dont1(void) {
printf("Don`t 1\n");
}
static inline void __dont2(void) {
printf("Don`t 2\n");
}
static inline void __dont3(void) {
printf("Don`t 3\n");
}
static inline void __dont4(void) {
printf("Don`t 4\n");
}
struct Callbacks* getNewCallback() {
struct Callbacks {
doit doer[4];
dont donters[4];
};
int i=0;
struct Callbacks* cb = (struct Callbacks*) malloc(
sizeof(struct Callbacks));
cb->doer[0]= __do1;
cb->doer[1]= __do2;
cb->doer[2]= __do3;
cb->doer[3]= __do4;
cb->donters[0] = __dont1;
cb->donters[1] = __dont2;
cb->donters[2] = __dont3;
cb->donters[3] = __dont4;
return cb;
}
int main(int argc, char** argv) {
struct Callbacks* cb = getNewCallback();
int i=0;
while ( i < 4 ) {
cb->doers[i]();
i++;
}
i=0;
while ( i < 4 ) {
cb->donters[i]();
i++;
}
}
When I ran it only the calls from doers array is called 7 times normally, and donters only one time. Why is that? When I call doers from the second loop, it prints the doers functions again....and only one call to donters is made to the first static inline donter functions __dont1()...