简体   繁体   中英

How to effectively handle the arguments when calling a generic function

I am trying to figure out what's the most efficient way to solve the following problem using C.

Let's consider a generic function

void foo(int x, int y);

Normally, the function would be called as follow:

int a = 1;
int b = 2;
int c = foo(a, b);

However, in my code I must use a genericCall function declared as:

int genericCall(void (*func)(void *), void *args, size_t size);

So for example, in order to execute the code above I must introduce an auxiliary function and a struct:

// Define a struct to store the arguments
struct foo_args {
    int x;
    int y;
}

// Auxiliary function
void foo_aux(void *args) {
    struct foo_args *args;
    int x, y;

    // Unpack the arguments
    args = (struct foo_args *) args;
    x = args->x;
    y = args->y;

    // Invocation of the original function
    foo(x, y);
}

// ...

// Pack the arguments in the struct
struct foo_args args;
args.x = 1;
args.y = 2;

// Call the generic function
genericCall(foo_aux, &args, sizeof(struct foo_args));

As you can imagine this approach does not scale very well: every time I want to call a different function I must add a lot of code that does very little apart from handling the arguments.

Is there a way to do the same without replicating all the code?

Thanks!

No, there is not much more that you can do. Your generic interface doesn't permit to pass type information, and if you have a function with multiple arguments that you want to pass, you have to place them to be accessible through a single pointer.

This is eg how coding with thread interfaces (POSIX or C11) usually works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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