简体   繁体   中英

How can I create a struct with a vTable or array of function pointers in C?

I am having a problem with declaring a struct with an array of function pointers (vTable) in C because if I declare the function pointer first and a parameter needs to be a self-referencial "this" pointer to itself , the struct hasn't yet been declared. If I declare the function pointer AFTER the struct, then the function type hasn't been declared so the compiler complains when I set up the struct:

#include <stdio.h>
#include <stdlib.h>
typedef int (*math_operation) (struct _MyClass *this,int a, int b);
typedef struct _MyClass{
    int number;
    char name[50];
    math_operation *vTable[50];
} MyClass;
int main(void)
{
    MyClass *test;
    return(EXIT_SUCCESS);
}

What is the proper way to create an array of function pointer which have a "this" pointer to the parent struct?

You just need a forward declaration of the struct in the global namespace:

struct MyClass_; 
typedef int math_operation(struct MyClass_ *this, int a, int b);

typedef struct MyClass_{
    int number;
    char name[50];
    math_operation *vTable[50];
} MyClass;

Things to note:

  1. I fixed the tag identifier, so it won't tread on the C standard .
  2. I changed the function pointer typedef into a function type typedef. You already defined vTable as an array of pointers to math_operation . One pointer declarator was superfluous. This also has the nice utility of allowing you to declare functions by their intended purpose, and have the compiler type check it:

     math_operation add; // .. Later int add(struct MyClass_ *this, int a, int b) { return a + b; } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM