【发布时间】:2018-03-16 03:55:02
【问题描述】:
我正在使用 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 中,我尝试声明一个 struct 对象并将 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:错误:被调用的对象不是函数或函数指针 (coptr->funcaddr)();
请说明调用函数指针的正确语法是什么。
【问题讨论】:
-
这里的问题是
void*只是一个通用的对象指针。您不能将其用于函数指针。但是,这是某些编译器上可用的常见非标准扩展。如果您需要在标准 C 中可移植的通用函数指针,最好在整数类型之间进行转换:uintptr_t -
如果函数指针是一个不同的变量或在
struct中,它没有任何区别。只需查阅您的 C 书籍,了解如何使用函数指针和声明类型。
标签: c