简体   繁体   English

传递的函数指针的参数

[英]Parameters of passed function-pointer

I was supposed to write C implementation of C++ STL container map (associative array) by hashtable (array of pointers to linked lists of data) and some supporting functions, ie inserting element, deleting table... I've successfully written all of these, except for one, which is foreach(table, function_ptr) function, which calls the passed function for all data in the table (printing contents...). 我应该通过哈希表(指向数据链表的指针的数组)和一些支持功能(例如,插入元素,删除表)编写C ++ STL容器映射(关联数组)的C实现。我已经成功编写了所有这些,除了其中一个,它是foreach(table, function_ptr)函数,该函数为表中的所有数据调用调用的函数(打印内容...)。

I'm a little stuck here because I can't figure out what parameters should be passed to function_ptr , so it would be universal. 我有点卡在这里,因为我不知道应该将哪些参数传递给function_ptr ,所以它将是通用的。 As for now, I don't think it's possible. 就目前而言,我认为这是不可能的。

If I would like just to pass a pointer for example to printf, it would be easy, prototype of foreach would look like this 如果我只想将指针传递给printf例如,这很容易, foreach原型看起来像这样

foreach(table_t *t, int (*function_ptr)(const char *fmt, ...))

and I would just call it for every data node like this 我会像这样为每个数据节点调用它

function_ptr("%s, %d\n", node.key, node.data)

but if I use this and change my mind someday that I would like to pass my own function, I would have to change the code of caller-function and the foreach function as well. 但是,如果有一天我想通过自己的函数使用此方法并改变主意,则还必须更改调用者函数和foreach函数的代码。

Is there any easy way to do something like this? 有没有简单的方法可以执行这样的操作?

The conventional way to specify "any argument type" is by using a void * like this: 指定“任何参数类型”的常规方法是使用void *如下所示:

foreach(table_t *t, int (*function_ptr)(void *p))

Then you can pass the address of each argument (which may be a complex data type, like a structure), and the function can cast it back to the appropriate type: 然后,您可以传递每个参数的地址(它可以是复杂的数据类型,如结构),然后该函数可以将其强制转换回适当的类型:

struct {
  int x;
  int y;
} numbers;

// Sums the numbers in a structure
int sum(void *p) {
  numbers *n = (numbers *) p;  // Cast back to the correct type
  return n->x + n->y;
}

// Counts the number of 'a' chars in a string
int numberOfA(void *p) {
  char *s = (char *) p;
  int num = 0;
  while (s != NULL && *s != '\0') {
    if (*s == 'a') {
      ++num;
    }
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM