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:
Best Answer
I wrote Lamda2Delegate struct for this purpose. Actually it converts c++11 lambda to any .net delegate.
The example of usage:
For your case:
To capture managed classes you need to wrap them with gcroot, and capture explicitly by value.
And the Lambda2Delegate.h itself
UPDATE: It is not possible to declare c++ lambda function inside managed member function, but there is workaround - use static member function: