how to call function pointer in a struct?

196 Views Asked by At

I am working with the xinu embedded operating system in c. I created a new header file and declared a struct:

struct callout {
   uint32 time;      /* Time of delay in ms */
   void *funcaddr;   /* Function pointer */
   void *argp;       /* Function arguments */
   uint32 cid;       /* Callout id for the specific callout */
   char *sample;
};

In my main, I try to declare a struct object and function the funcaddr to a function.

void test();

process main(void) {
   struct callout *coptr;

   coptr->sample ="hellowolrd";
   coptr->funcaddr = &test;

   (coptr->funcaddr)(coptr->argp);    //error here
   kprintf("coptr %s \n", coptr->sample);

   return OK;

 }

 void test() {
    kprintf("this is the test function \n");
 }

I try to invoke the function pointer through the struct but I am getting an error:

main.c:30:19: error: called object is not a function or function pointer
    (coptr->funcaddr)();

Please show what is the correct syntax to invoke the function pointer.

1

There are 1 best solutions below

2
On BEST ANSWER

You have declared funcaddr as an object pointer. To declare a function pointer it looks like this:

struct callout {
   uint32 time;
   void (*funcaddr)();  // <-------- function pointer

Then the rest of your code should work.


If you didn't see an error message for the line coptr->funcaddr = &test; then I would recommend adjusting your compiler settings, it's important to have the information available that the compiler can tell you.