Search code examples
c++-cli

Workaround for not having lambdas that can capture managed variables


In C++/CLI, you cannot create managed lambdas (like you can in C#), and thus you can't capture managed variables. You can create regular methods (rather than lambdas), but you are still left without being able to capture managed variables.

Is there a standard workaround to employ in C++/CLI code? In other words I'm looking for a standard pattern I could use in C++/CLI to do the following from C#:

class A { }

class B
{
    void Foo()
    {
        A a = new A();
        Func<A> aFunc = () => a; // Captures a
    }
}

I could

  • Create a member variable for each variable I want to capture, and then in the delegate use that member variable. This wouldn't work in the general case as you might have two invocations of the method that want to work on different captured a's, but it would work for the common case.
  • Create a nested class that does the capturing in its ctor, and then use a method of this nested class as the delegate. This should work in the general case, but it means I need a nested class every time I want to capture different variables.

Question: Is there a better option than the ones above, or which option above would be your go-to approach?

Related Questions:


Solution

  • If you look at a decompilation of a C# lambda, you'll see that the C# compiler does the same thing as your option #2. It's annoying to create a bunch of single-use classes, but that's what I'd recommend.

    With a C# lambda, when it creates the nested class instance, it uses that everywhere instead of the local variable. Keep that in mind as you write the method that uses the nested class.