I have a struct with a callback function, the callback function needs a pointer to the structure in order to do its operation. How do I properly define these elements such t
something like this
typedef struct _pr_PendingResponseItem_ {
// some fields required for processing...
int (*doAction)(struct _pr_PendingResponseItem_ *pr);
} pr_PendingResponseItem;
should fix it.
(Tested & works)
There are two ways to do it — for both your example structures. They are essentially isomorphic.
Use a structure tag, as already shown in various other answers.
typedef struct pr_PendingResponseItem
{
// some fields required for processing...
int (*doAction)(struct pr_PendingResponseItem *pr);
} pr_PendingResponseItem;
typedef struct LinkedItem
{
struct LinkedItem *prev;
struct LinkedItem *next;
void * data;
} LinkedItem;
Use typedef
to give a name to an incomplete structure type and use the typedef
in the structure definition.
typedef struct pr_PendingResponseItem pr_PendingResponseItem;
struct pr_PendingResponseItem
{
// some fields required for processing...
int (*doAction)(pr_PendingResponseItem *pr);
};
typedef struct LinkedItem LinkedItem;
struct LinkedItem
{
LinkedItem *prev;
LinkedItem *next;
void * data;
};
Note that the structure tags are in a different namespace from the typedef
names, so there is no need to use different names for the typedef
and structure tag. Also note that in C++ the typedef
would be unnecessary.
Adding to the answer by nos above.
The key insight here is that when dealing with a declaration like "typedef struct name1 {} name2;", you are actually declaring two types i.e. "struct name1 {};" and then "typedef struct name1 name2;", where "struct name1" is a type and you have to use the syntax "struct name1" to refer to it, and "name2" is a type, and you refer to it as "name2". You are allowed to leave "name1" out, in which case you just define the second type and the first one remains a anonymous struct.
Now, in the first case, if you want to refer to the type "struct pr_PendingResponseItem", you need to declare that type, instead of the anonymous struct you have declared. So, change your struct declaration to "struct pr_PendingResponseItem".
In the second case, you are trying to refer to a struct type as a forward reference (i.e. referring to it before its definition is complete), which is allowed, but to refer to a struct type, the required syntax is "struct name". So you need to replace forward references to "LinkedItem_" in your definition with "struct LinkedItem_".
Your function pointer references a struct pr_PendingResponseItem, but you haven't declared a struct pr_PendingResponseItem. You just have an unnamed structure typedef'ed to the name pr_PendingResponseItem (and that name isn't established yet).
Give the struct a name:
struct pr_PendingResponseItem {
// some fields required for processing...
int (*doAction)(struct pr_PendingResponseItem *pr);
} ;
typedef struct pr_PendingResponseItem pr_PendingResponseItem;