1

i have problem with understanding below struct in c language ! i understand what is a struct and what it use for but this one seems weird for me and i can't see the standard form of struct like it's described in c learning websites like www.geeksforgeeks.org !

It's nothing more in code about this struct !

typedef struct sIMasterConnection* IMasterConnection;

struct sIMasterConnection {
    bool (*isReady) (IMasterConnection self);
    bool (*sendASDU) (IMasterConnection self, CS101_ASDU asdu);
    bool (*sendACT_CON) (IMasterConnection self, CS101_ASDU asdu, bool negative);
    bool (*sendACT_TERM) (IMasterConnection self, CS101_ASDU asdu);
    void (*close) (IMasterConnection self);
    int (*getPeerAddress) (IMasterConnection self, char* addrBuf, int addrBufSize);
    CS101_AppLayerParameters (*getApplicationLayerParameters) (IMasterConnection self);
    void* object;
};
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • See [**How do function pointers in C work?**](https://stackoverflow.com/questions/840501/how-do-function-pointers-in-c-work) – Andrew Henle Jun 26 '23 at 10:35
  • Understanding this has nothing to do with structs as such. As a side note, it is sometimes considered bad practice to dump a bunch of function pointers in a struct instead of using a separate "vtable", but that's an advanced topic. – Lundin Jun 26 '23 at 10:45

1 Answers1

0

All data members of the structure except this one

void* object;

are pointers to functions.

For example this data member

bool (*isReady) (IMasterConnection self);

declares a pointer to function that has return type bool and one parameter of the type IMasterConnection that is an alias for the pointer type declared like

typedef struct sIMasterConnection* IMasterConnection;

That is the parameter self has the type of a pointer to an object of the type struct sIMasterConnection.

To make it clear consider a simple demonstration program where there is declared a pointer to a function.

#include <stdio.h>

void f( void )
{
    puts( "Hello, World!" );
}

int main( void )
{
    void ( *pf )( void ) = f;

    pf();
}

The program output is

Hello, World!

A similar way as there is declared the saclar variable pf you may declare a data member of a struture.

#include <stdio.h>

void f( void )
{
    puts( "Hello, World!" );
}

int main( void )
{
    struct A
    {
        void ( *pf )( void );
    };

    struct A a = { .pf = f };

    a.pf();
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335