开发者

passing a function as a parameter

void dispatch_for(dispatch_queue_t *queue, long number, void (* work)(long)){
    int loop = number;
    int i;
    task_t *ctask;
    for(i = 0; i<loop;i++){
        ctask = create_task((void *)work,number,"for_test");
        dispatch_async(queue,ctask);
    }
}    

task_t *task_create(void (* work)(void *), void *param, char* name){

    //do something
}

I'm getting work as a function and need to pass it to the function create_task开发者_高级运维..(1st parameter)

How should i pass it?


name of the function without the parentheses is the pointer to that function :

void work(void) {
...;
}

void main(void) {
task_create(work, void, void);
}


Just use the identifier like any other parameter:

dispatch_for(queue, number, work);


The easiest thing would be a typedef to the wanted function type. So you can do

typedef void workfunc_t(void *);

workfunc_t sample_workfunc; // in order to ensure type-correctness

void workfunc_t(void *)
{
    // ...
}

void dispatch_for(dispatch_queue_t *queue, long number, workfunc_t * work)
{
    int loop = number;
    int i;
    task_t *ctask;
    for(i = 0; i<loop;i++) {
        ctask = create_task(work, number, "for_test");
        dispatch_async(queue,ctask);
    }
}

task_t *task_create(workfunc_t work, void *param, char* name){
    //do something
}


The function work doesn't have the same signature in dispatch_for and task_create (the argument is a pointer in one, a long in the other)

It seems strange you want to use the same function in both cases


Since you're using C, and work is a type void (*)(long), but you want to make it a void (*)(void*), simply re-cast the type of work (this is can be done the easiest by using a typedef)

//declare somewhere at a global level
typedef void (*task_create_func)(void*);

//at the point where you want to call task_create
task_create((task_create_func)work, PARAM1, PARM2);

Alternatively, if you don't want to deal with typedefs, you can simply do the cast using the desired pointer-type at the point-of-call like so:

task_create((void (*)(void*))work, PARAM1, PARAM2); 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜