0

We have a structure

typedef struct _disis_thinkgear
{
    t_object x_obj;

    //other members and such

and we need to have a member in the structure be a function like

    void (*handleDataValue)( ????  , unsigned char extendedCodeLevel, 
                               unsigned char code, unsigned char numBytes,
                               const unsigned char *value, void *customData );
} t_disis_thinkgear;

How can the ???? be replaced so that x is the first argument ? To use as

x->handleDataValue =  //another function

2 Answers 2

2

You'll need to forward-declare the typedef:

typedef struct _disis_thinkgear t_disis_thinkgear;

Then you can use the type in the definition of the structure:

struct _disis_thinkgear {
    ...

    void (*handleDataValue)(t_disis_thinkgear *x, ...
};

Once you've got an object of this type, you'd call the function as:

t_disis_thinkgear *x = ...
x->handleDataValue(x, ...);
Sign up to request clarification or add additional context in comments.

4 Comments

can't you just write something like void (*handleDataValue)(struct _disis_thinkgear *x, ... inside the struct?
@AlexReinking You can, but the forward-declare is better because then you don't have to special-case uses of the type within the struct.
@AlexReinking Also, some compilers will output the type as written in error messages. Having t_disis_thinkgear show up in error messages would likely be preferable to seeing struct _disis_thinkgear.
@JimBalter Well-argued. +1
1

This is a full example that works. You can actually use struct _disis_thinkgear from within the struct.

#include <stdlib.h>
#include <stdio.h>

typedef struct _disis_thinkgear {
        // ... other things ...

        void (*handleDataValue)(struct _disis_thinkgear *);

        // ... other things ...
} t_disis_thinkgear;

void printSomething(t_disis_thinkgear *foo) {
        printf("argument is %p\n", foo);
}

int main()
{
        t_disis_thinkgear *x = malloc(sizeof(x));
        x->handleDataValue = &printSomething;
        x->handleDataValue(x);
        free(x);
        return 0;
}

1 Comment

Or you can typedef the struct as a partial type and avoid the inconsistent usage: typedef struct _disis_thinkgear t_disis_thinkgear; struct _disis_thinkgear { ... void (*handleDataValue)(t_disis_thinkgear *); ... };

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.