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

C: Putting a function pointer in a structure where the function uses that structure as an argument

我好像运行陷入了先有鸡还是先有蛋的问题。

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

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

以下是我目前拥有的:

#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")

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

所以我通过堆栈交换进行了搜索,但找不到任何让我感到羞愧的问题。就在我即将写完所有内容时,我瞥了一眼右边的 "Similar Questions" 框,我碰巧看到了以下我以前没有遇到过的问题:

How to properly define a function pointer in struct, which takes struct as a pointer?

在它的回答中我找到了我的答案。我只需要在结构本身中定义函数指针,而不是事先定义。 (我试过,但忘记在定义中包含 struct 关键字,所以它不起作用,因为我猜类型 def 不完整)。

以下是编译干净且似乎有效的内容:

#include <stdio.h>

typedef struct IO_config_t{
  int                   address;
  void                  (*IO_fun_ptr)(struct IO_config_t *); //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);
}

使用forward-declarations.

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

#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