C - passing a function with arguments to the wrapper executor

Is there a way to create a wrapper in C as follows:

void wrapper(void *func) {
  // Set up
  func([same arguments as func was passed in with]);
  // Clean up
}

void foo(int x, int y);
void bar(char *z);

wrapper(foo(1, 2));
wrapper(bar("Hello"));

It seems that you need to either go within the means within wrapper, or support only one type of method header for func. I wrote a lot of Javascript ... and of course, this is possible in JS.

+4
source share
2 answers

This is the best I can come up with with the Variadic function wwrappers:

#include <stdio.h>
#include <stdarg.h>

void wrapper(void (*func)(va_list), ...) {
    va_list args;
    va_start(args, func);

    func(args);

    va_end(args);
}

void foo(int x, int y)
{
    printf("foo(%d,%d)\n", x, y);
}
void vfoo(va_list args)
{
    foo(va_arg(args, int), va_arg(args, int));
}
void bar(char *z)
{
    printf("bar(%s)\n", z);
}
void vbar(va_list args)
{
    bar(va_arg(args, char*));
}

int main()
{
    wrapper(vfoo, 1, 2);
    wrapper(vbar, "Hello, World!");
    return 0;
}

Live example at Coliru .

+4
source

Do you consider (ab) using a preprocessor?

#include <stdio.h>

#define wrapper(f) /* Set up   */\
                   f;            \
                   /* Clean up */

void foo(int x, int y) {
    printf("x: %d; y: %d\n", x, y);
}

void bar(char *str) {
    printf("str: %s\n", str);
}

int main(void) {
    wrapper(foo(42, 11));
    wrapper(bar("hello world"));
}

, ab- (ab), , , , populus. , , , , , . , , , .

, " Javascript, , , Javascript...".

, , , , , C... , .

, Javascript .

#include <stdio.h>

struct argument;
typedef struct argument argument;
typedef void function(argument *);

struct argument {
    function *function;

    /* for foo() */
    int x;
    int y;

    /* for bar() */
    char *str;
};

void wrapper(argument *a) {
    // set up
    a->function(a);
    // clean up
}

void foo(argument *a) {
    printf("x: %d; y: %d\n", a->x, a->y);
}

void bar(argument *a) {
    printf("str: %s\n", a->str);
}

#define foo(...) wrapper(&(argument){ .function = foo, __VA_ARGS__ })
#define bar(...) wrapper(&(argument){ .function = bar, .str = "", __VA_ARGS__ })

int main(void) {
    foo(.x = 42, .y = 11);
    bar(.str = "hello world");
}

:

  • , - , , printf scanf, , / . :
  • , foo bar. str "" ( ) bar.
  • wrapper, ( , Javascript). , , wrapper ? .
  • , , .

, , foo, bar , . , , , , , - .

- default_foo default_bar - ...

, , ... , , ( ), .

+3

Source: https://habr.com/ru/post/1617256/


All Articles