You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Xinu嵌入式系统中C语言结构体函数指针的正确调用方法

解决结构体中函数指针的调用错误问题

首先,你的代码存在两个关键问题导致了编译错误,我们一步步来修复:

1. 函数指针类型不匹配

你把struct callout里的funcaddr定义成了void *,但在C语言中,void*是通用数据指针,编译器不会自动将它识别为函数指针。要解决这个问题,我们需要明确把funcaddr定义为函数指针类型。

先给函数指针定义一个类型别名(让代码更易读,避免重复写复杂的函数指针声明):

// 定义函数指针类型:指向接收void*参数、返回void的函数
typedef void (*callout_func)(void*);

然后修改struct callout的定义,将funcaddr的类型从void*改为callout_func:

struct callout {
   uint32 time;      /* Time of delay in ms */
   callout_func funcaddr;   /* 现在是正确的函数指针类型 */
   void *argp;       /* Function arguments */
   uint32 cid;       /* Callout id for the specific callout */
   char *sample;
};

2. 未初始化指针的未定义行为

你声明了struct callout *coptr;但没有给它分配内存!直接通过空指针访问成员(比如coptr->sample)会触发未定义行为,可能导致崩溃或奇怪的运行错误。在Xinu系统中,需要用getmem函数分配内存:

coptr = (struct callout *)getmem(sizeof(struct callout));
// 建议检查内存分配是否成功
if (coptr == NULL) {
    kprintf("Failed to allocate memory for callout\n");
    return SYSERR;
}

3. 调整test函数的参数匹配

你调用函数指针时传入了coptr->argp(void*类型),所以test函数的参数要和这个类型匹配,同时修改函数声明让它更明确:

// 明确声明函数参数类型
void test(void *arg);

process main(void) {
   struct callout *coptr;

   // 分配内存
   coptr = (struct callout *)getmem(sizeof(struct callout));
   if (coptr == NULL) {
       kprintf("Memory allocation failed\n");
       return SYSERR;
   }

   coptr->sample = "helloworld"; // 修正拼写错误
   coptr->funcaddr = test; // 函数名本身就是指针,无需&符号

   // 现在可以正常调用函数指针了
   coptr->funcaddr(coptr->argp);
   kprintf("coptr %s \n", coptr->sample);

   // 用完内存后记得释放(如果不再需要)
   freemem((char *)coptr, sizeof(struct callout));

   return OK;
}

void test(void *arg) {
    kprintf("this is the test function \n");
    // 如果需要使用传入的arg参数,在这里处理即可
}

错误原因解释

编译器看到(coptr->funcaddr)(coptr->argp)时,coptr->funcaddr是void*类型,它无法识别这个指针指向的是函数,因此报错“called object is not a function or function pointer”。只有当变量的类型是明确的函数指针时,编译器才允许你像调用函数那样使用它。

内容的提问来源于stack exchange,提问作者simhuang

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 10:13:23