如何在结构中调用函数指针?

how to call function pointer in a struct?

我正在使用 c 语言的 xinu 嵌入式操作系统。我创建了一个新的头文件并声明了一个结构:

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;
};

在我的 main 中,我尝试声明一个结构对象并将 funcaddr 函数化为一个函数。

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");
 }

我尝试通过结构调用函数指针,但出现错误:

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

请说明调用函数指针的正确语法是什么。

您已将 funcaddr 声明为对象指针。要声明一个函数指针,它看起来像这样:

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

那么您的其余代码应该可以正常工作。


如果您没有看到第 coptr->funcaddr = &test; 行的错误消息,那么我建议您调整编译器设置,重要的是要有编译器可以告诉您的可用信息。