1

我有一个函数需要这样的参数

void priqueue_init(priqueue_t *q, int(*comparer)(void *, void *))

我希望它能够接受任何类型的参数。

在一个单独的文件中,我首先 typedef

typedef int (*comp_funct)(job_t*, job_t*);

而我想传递的功能......

int fcfs_funct1(job_t* a, job_t* b)
{
  int temp1 = a->arrival_time;
  int temp2 = b->arrival_time;

  return (temp1 - temp2);
}

对 priqueue_init 的调用:

priqueue_init(pri_q, choose_comparator(sched_scheme));

最后,我的 choose_comarator 函数:

comp_funct choose_comparator(scheme_t scheme)
{
    if (sched_scheme == FCFS)
        return fcfs_funct1;

    return NULL;
}

我在调用 priqueue_init 时出错。

    libscheduler/libscheduler.c: In function ‘add_to_priq’:
libscheduler/libscheduler.c:125:3: error: passing argument 2 of ‘priqueue_init’ from incompatible pointer type [-Werror]
In file included from libscheduler/libscheduler.c:5:0:
libscheduler/../libpriqueue/libpriqueue.h:25:8: note: expected ‘int (*)(void *, void *)’ but argument is of type ‘comp_funct’

我在哪里挂机?定义 priqueue_init 的文件不知道类型 job_t。我认为使用无效的论点是要走的路。

4

2 回答 2

3

int (*comparer)(void *, void *)并且int (*comp_funct)(job_t*, job_t*)不是兼容的类型。更改它们以匹配,或添加类型转换。

指针(void *job_t *你的情况下)不必是相同的大小,所以编译器正确地给你一个错误。由于它们大多数机器上的大小相同,因此简单的类型转换可能会解决您的问题,但您会引入一些潜在的不可移植性。

于 2013-10-23T21:46:47.523 回答
2

为了与函数类型签名兼容,您的比较函数必须接受void*参数,并在内部进行转换:

int fcfs_funct1(void* a, void* b)
{
  int temp1 = ((job_t*)a)->arrival_time;
  int temp2 = ((job_t*)b)->arrival_time;

  return (temp1 - temp2);
}
于 2013-10-23T21:48:44.980 回答