C:将函数指针放在结构中,函数使用该结构作为参数

标签 c function struct function-pointers

我好像遇到了先有鸡还是先有蛋的问题。

我想要一个结构,其成员之一是函数指针。然而,这个函数指针想要使用与它的参数相同的结构。这会产生一个问题,我必须先定义函数指针,然后才能将其作为成员包含在内,但在定义结构之前我无法正确定义它。

我发现,如果我只是将函数指针的参数列表留空,它似乎可以工作,尽管我读到的是这可能充满问题。

下面是我目前拥有的:

#include <stdio.h>

typedef void (*IO_fun_ptr_t)();

typedef struct IO_config_t{
  int                   address;
  IO_fun_ptr_t          IO_fun_ptr; //pointer to the function to be used
} IO_config_t;

void print_address (IO_config_t *input){
  printf("The address is %d \n", input->address);
  printf("Push any key to continue:");
  getchar();
}

void main()
{
  IO_config_t             input = {.address = 16,
                                   .IO_fun_ptr = &print_address};

  input.IO_fun_ptr(&input);

}

结果是:

The address is 16 
Push any key to continue:

这可行,但我担心将该参数留空的潜在影响。

顺便说一句,我最初认为我应该能够使用 void* 作为参数作为指向未知参数类型的指针的占位符,但是在我这样做的时候我会遇到编译错误将指针分配给我的函数:

typedef void (*IO_fun_ptr_t)(void *);

(Error[Pe144]: a value of type "void (*)(IO_config_t *)" cannot be used to initialize an entity of type "IO_fun_ptr_t")

关于如何更好更清洁地执行此操作的任何建议?

最佳答案

使用前向声明。

这是一种声明结构存在的方式,但直到稍后才提供结构的所有成员的详细信息。

#include <stdio.h>

// 1.) Forward declaration: Here is the name of the structure
// but member-details are omitted.
struct IO_config_t;

// 2.) typedef of the structure
// Still no details on the members.
typedef struct IO_config_t  IO_config_t;

// 3.) The parameter to the function is listed, using the definition
// from step 2.)  (note: Still no details on the members yet)
typedef void (*IO_fun_ptr_t)(IO_config_t* input);

// 4.) Now we actually detail the members of the structure
struct IO_config_t{
  int                   address;
  IO_fun_ptr_t          IO_fun_ptr;
};

void print_address (IO_config_t *input){
  printf("The address is %d \n", input->address);
  printf("Push any key to continue:");
  getchar();
}

void main()
{
  IO_config_t input = {.address    = 16,
                       .IO_fun_ptr = &print_address};

  input.IO_fun_ptr(&input);

}

这在短程序中得到了演示:https://ideone.com/p3jBYt

关于C:将函数指针放在结构中,函数使用该结构作为参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48992874/

相关文章:

c - 在 C90 中将 malloc 用于双指针

javascript Canvas 功能在没有警报的情况下无法正常工作

javascript - 如何正确创建一个textNode并附加到特定位置?

java - 有没有有效的方法使用 JNA 读取动态大小共享内存段?

c - 将可执行文件链接到可加载模块的可移植性如何?

c - 获取以逗号分隔的数字

javascript - 如何在laravel中调用 ' '标记的路线

c - 成员分配是否保留了结构填充字节?

c - C 中带有 typedef 结构的未知类型名称

c - 警告 : format argument is not a pointer (arg 2)?