Home > Mobile >  Wrap a C lambda with another lambda
Wrap a C lambda with another lambda

Time:06-14

I am trying to get the contents of a lambda in c and creating another function from it. A minimal example that would be ideal is something like:

auto A = []{ some_function(args); };
auto B = []{ return /*Contents of A*/; };
// Ideally this would translate to
auto B = []{ return some_function(args); };

Macros could work, but I would like to avoid them. I have tried a few things but I can't seem to find if there is a way to get the content of a lambda (not only the return it could have), and write code around it. There might not be a way, but I wanted to be sure.

One of the applications of this that I would be curious about is to write a simple unit test as:

Test a = []{
    check(1 == 1);
    check(2 == 1);
};

And have a wrapper around all test functions that could be like:

[]{
    for (line : /*Contents of A*/) {
        print("Evaluating {}...", line);
        if (not line)
            print("Failed test");
    }
};

So if A = F1, F2, F3, ..., you can create B(A) = B(F1), B(F2), B(F3), ...

CodePudding user response:

After C code has been compiled, there is no standard way to get information about its source code or modify the source code in the ways you are looking for. Most C implementations turn the source code into machine code (i.e. assembly instructions) and run it through an optimizer that can reorder or remove the code as long as the observable behavior of the code is still the same.

The only thing I can think of is very complex and it's not even a complete solution: if you ship your program with a copy of its own source code and all the headers it relies on, then you could link against libclang and use that to parse the C source code and get detailed information about every AST node. This would add a lot of complexity to your program so it's probably not worth it.

  • Related