4
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?

Vinicius Kamakura
  • 7,665
  • 1
  • 29
  • 43
Leanne
  • 667
  • 3
  • 11
  • 23
  • 3
    Are `create_task` and `task_create` supposed to be the same function ? – Paul R Aug 12 '11 at 12:22
  • 2
    What's the error/problem? You should be able to just pass `work` verbatim. Also check your spelling, is it `task_create` or `create_task`? Best though to say `typedef void (*workfunction)(void*);`, then you can cast `(workfunction)work` if necessary. – Kerrek SB Aug 12 '11 at 12:23

5 Answers5

4

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

void work(void) {
...;
}

void main(void) {
task_create(work, void, void);
}
phoxis
  • 60,131
  • 14
  • 81
  • 117
Matthieu
  • 4,605
  • 4
  • 40
  • 60
1

Just use the identifier like any other parameter:

dispatch_for(queue, number, work);
Karl Bielefeldt
  • 47,314
  • 10
  • 60
  • 94
1

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); 
Jason
  • 31,834
  • 7
  • 59
  • 78
1

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
}
glglgl
  • 89,107
  • 13
  • 149
  • 217
1

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

Doraj
  • 86
  • 4