I have a interface documented like this:
typedef struct Tree {
int a;
void* (*Something)(struct Tree* pTree, int size);
};
Then as I understand I need to create instance of it, and use Something method to put the value for 'size'. So I do
struct Tree *iTree = malloc(sizeof(struct Tree));
iTree->Something(iTree, 128);
But it keeps failing to initialize. Am I doing this right? Howcome the first member of the Something method is pointer to the very same struct?
Can anyone explain please?
Thanks
You have to set Something
to something since it is only a function pointer and not a function. The struct you created with malloc just contains garbage and struct fields need to be set before it is useful.
struct Tree *iTree = malloc(sizeof(struct Tree));
iTree->a = 10; //<-- Not necessary to work but you should set the values.
iTree->Something = SomeFunctionMatchingSomethingSignature;
iTree->Something(iTree, 128);
Update
#include <stdlib.h>
#include <stdio.h>
struct Tree {
int a;
//This is a function pointer
void* (*Something)(struct Tree* pTree, int size);
};
//This is a function that matches Something signature
void * doSomething(struct Tree *pTree, int size)
{
printf("Doing Something: %d\n", size);
return NULL;
}
void someMethod()
{
//Code to create a Tree
struct Tree *iTree = malloc(sizeof(struct Tree));
iTree->Something = doSomething;
iTree->Something(iTree, 128);
free(iTree);
}
This is a poor man's virtual function. The initial parameter is roughly equivalent to C++'s this
pointer in a member function. And you must manually set the function pointers before calling them, whereas C++ virtual functions are set up by the compiler.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With