Search code examples
coopstructfunction-pointers

How to place a function pointer in a c struct whereas the input parameter of the function pointer is the struct itself (i.e. "this" pointer in c)


I am trying to use a function pointer inside a struct, whereas the function pointer needs an instance of the struct itself as argument. My current code snippet looks like this:

#include "stdio.h"
#include "stdint.h"

typedef struct MYSTRUCT_S MYSTRUCT;

typedef struct {
  int (*isInRange)(const MYSTRUCT* pDataPoint, const uint16_t newValue);
  const uint16_t minValue;
  const uint16_t maxValue;
} MYSTRUCT_S;

int isInRange(const MYSTRUCT* pDataPoint, const uint16_t newValue) {
  MYSTRUCT* mDatapoint = (MYSTRUCT*)pDataPoint;
  if ((newValue < mDatapoint->minValue) || (newValue > mDatapoint->maxValue)) {
    return 0;
  } else {
    return 1;
  }
}

int main() {
static MYSTRUCT* maDataPoint = NULL;
maDataPoint->isInRange(maDataPoint, 6);
return 0;
}

The compiler complains about: error: invalid use of incomplete typedef 'MYSTRUCT' {aka 'struct MYSTRUCT_S'}"

I was already reading through the following items, but could not find the solution for my issue:

Any idea, how I could solve this issue?


Solution

  • Consolidating the comments of @Barmar and the answer of @ikegami, we get:

    #include "stdio.h"
    #include "stdint.h"
    
    typedef struct MYSTRUCT_S MYSTRUCT;
    
    typedef struct MYSTRUCT_S {
      int (*isInRange)(const MYSTRUCT* pDataPoint, const uint16_t newValue);
      const uint16_t minValue;
      const uint16_t maxValue;
    } MYSTRUCT_S;
    
    int isInRange(const MYSTRUCT* pDataPoint, const uint16_t newValue);
    
    int specificImplementation(const MYSTRUCT* pDataPoint, const uint16_t newValue) {
        return 42;
    }
    
    int main() {
    static MYSTRUCT maDataPoint = {&specificImplementation, 0, 100};
    
    return maDataPoint.isInRange(&maDataPoint, 6);
    }
    

    In the above example, maDataPoint is an instance of MYSTRUCT which gets initialized to reference specificImplementation which is a function with the same signature as the declaration of isInRange. The compiler checks for us that specificImplementation matches the signature (both arguments and return type) of isInRange.