3

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.

phuclv
  • 37,963
  • 15
  • 156
  • 475
simhuang
  • 495
  • 3
  • 8
  • 20
  • The problem here is that `void*` is only a generic object pointer. You can't use it for function pointers. However, that is a common non-standard extension available on some compilers. If you need generic function pointers portably in standard C, it is better to convert to/from an integer type: `uintptr_t` – Lundin Mar 16 '18 at 07:45
  • IT does not make any difference if the function pointer is a distinct variable or within a `struct`. Just consult your C book for how to use function pointers and declare types. – too honest for this site Mar 17 '18 at 16:55

1 Answers1

4

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.

M.M
  • 138,810
  • 21
  • 208
  • 365
  • Your answer is perfect and thanks for the advice. I have a couple more questions: 1) Can you show me the syntax to cast a object pointer to function? 2) How can I pass my struct variable argp into the function as arguments? Yeah the compiler didn't give me an error regarding that. I will look into it. Thanks for the advice. – simhuang Mar 16 '18 at 04:06
  • 1
    @simhuang Your code for passing `argp` is already correct. You don't need to use any casts. (If you did want to cast for some reason then it is the same as any other cast you put the type name in the brackets. E.g. `(void(*)())objp` – M.M Mar 16 '18 at 04:16