如何使用包装函数传入函数的参数指针函数?

时间:2014-12-15 01:14:57

标签: c pthreads wrapper

我有这个功能:

void boot(uint ncores, uint nterm, Task boot_task, int argl, void* args)
{

 for(int i=0; i<MAX_PROC;i++) {
    PT[i].ppid = NOPROC;
 }
 nextproc = 0;

 curproc = NOPROC;
 Exec(boot_task, argl, args);
}

并且我想要而不是使用Exec()来使用pthread,所以我必须调用cpu_boot:

void cpu_boot(uint cores, interrupt_handler bootfunc, uint serialno)
{
 //I cannot change this function 
}

这些是参数的类型

typedef void interrupt_handler();
typedef int (* Task)(int, void*);

我试过了:

void boot(uint ncores, uint nterm, Task boot_task, int argl, void* args)
{
    void my_wrapper()
    {

        int y;
        y= boot_task(argl, args);
    }

    cpu_boot(ncores, my_wrapper , nterm);
}

但这是错误的。我该如何实现呢?

2 个答案:

答案 0 :(得分:2)

你会想要这样的东西:

void some_interrupt_handler(){
    /* code here */
    return;
}

interrupt_handler* my_wrapper(Task boot_task, int argl, void* args)
{
    /* 
      this is where you run boot task
    */
    boot_task(argl, args);

    /* then pick an interrupt_handler to return... */
    void (*function_ptr)() = some_interrupt_handler;

    return function_ptr;
}

然后你可以像这样使用你的包装器:

void boot(uint ncores, uint nterm, Task boot_task, int argl, void* args)
{
    cpu_boot(ncores, my_wrapper(boot_task, argl, args) , nterm);
}

答案 1 :(得分:1)

更通用,更灵活的方式......

void some_interrupt_handler(){
    /* code here */
    return;
}

typdef struct boot_data_struct {
    int argc;
    void * argv;
    Task boot_task;
    interrupt_handler * handler;
} boot_data;

interrupt_handler* my_wrapper(void * data)
{
    boot_data * bootData = data;

    /* 
      this is where you run boot task
    */
    data->boot_task(bootData->argc, bootData->argv);

    return bootData->handler;
}

然后你可以像这样使用你的包装器:

void boot(uint ncores, uint nterm, Task boot_task, int argl, void* args)
{
    boot_data * data = malloc(sizeof *data); 
    //remember to memset if you arent going to fill out all variables!
    data->argc = argl;
    data->argv = args;
    data->boot_task = boot_task;
    data->handler = some_interrupt_handler;

    cpu_boot(ncores, my_wrapper(data) , nterm);

    free(data);
}