C# lambda 函数的含义和C++翻译

C# lambda function meaning and C++ translation

本文关键字:C++ 翻译 lambda 函数      更新时间:2023-10-16

我正在尝试从 C# 转换为C++我在 Internet 上找到的图像的过滤函数,以便我可以编译一个 DLL 并在我的项目中使用它。原始 C# 代码为:

    Parallel.For(0, height, depthArrayRowIndex => {
        for (int depthArrayColumnIndex = 0; depthArrayColumnIndex < width; depthArrayColumnIndex++) {
            var depthIndex = depthArrayColumnIndex + (depthArrayRowIndex * width);
            .
            .
            .
            ... other stuff ...
    }

我问题的第一部分是:如何

    depthArrayRowIndex => {

工程?depthArrayRowIndex的含义是什么:

    var depthIndex = depthArrayColumnIndex + (depthArrayRowIndex * width);

这是我C++翻译:

    concurrency::parallel_for(0, width, [&widthBound, &heightBound, &smoothDepthArray] () {
        for (int depthArrayColumnIndex = 0; depthArrayColumnIndex < width; depthArrayColumnIndex++) {
            int depthIndex = depthArrayColumnIndex + (depthArrayRowIndex * width);
            .
            .
            .
            ... other stuff ...
    }

但显然depthArrayRowIndex在这里没有任何意义。如何在C++中翻译工作代码中的 C# 代码?

非常感谢!! :-)

在本例中,"depthArrayRowIndex" 是 lambda 函数的输入参数,因此在C++版本中,您可能需要更改

[&widthBound, &heightBound, &smoothDepthArray] () 

[&widthBound, &heightBound, &smoothDepthArray] (int depthArrayRowIndex)

如果您想进一步了解 C# lambda 语法,此链接可能很有用

http://msdn.microsoft.com/en-us/library/vstudio/bb397687.aspx

Foo => {
  // code
  return bar; // bar is of type Bar
}

(Foo) => {
  // code
  return bar; // bar is of type Bar
}

将其转换为C++

[&](int Foo)->Bar {
  // code
  return bar; // bar is of type Bar
}

屁股Foo属于int型。 在C++中,单行 lambda 可以跳过->Bar部分。 不返回任何内容的 Lambda 可以->void跳过。

您可以在C++ lambda 的[]中列出捕获的参数(以及它们是否由值或引用捕获(,但 C# lambda 相当于捕获智能引用隐式使用的所有内容。 如果 lambda 的生存期限制在创建 lambda C++的范围内,则[&]是等效的。

如果它可以持续更长时间,您需要处理 lambda 捕获的数据的生命周期管理,并且您需要更加小心并且仅按值捕获(并且可能在捕获shared_ptr之前将数据打包到shared_ptr中(。

depthArrayRowIndex基本上是(并行(外部for循环的索引变量/值。它将从0包容性变为height独家:

http://msdn.microsoft.com/en-us/library/dd783539.aspx

一点解释(C#(:并行的整个第三个参数是lambda函数,该操作获取一个Int32参数,它恰好是循环索引。

所以我认为你的C++翻译应该从: concurrency::parallel_for(0, height, ...而不是width.