2013-06-25 31 views
0

我想從C#翻譯爲C++過濾函數的圖像,我在互聯網上找到,所以我可以編譯一個DLL,並在我的項目中使用它。 原來的C#代碼:C#lambda函數的意義和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#代碼?

謝謝你非常非常多! :-)

+1

這是lambda的一個參數。 –

+0

對不起...我很愚蠢!你能否更好地解釋一下lambda函數的參數是什麼? – Apache81

+0

將某物傳遞給lambda,與參數 –

回答

3

在這種情況下, 「depthArrayRowIndex」 是lambda函數的輸入參數,所以在你的C++版本,您可能需要更改

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

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

如果您想了解C#lambda語法進一步閱讀,這個環節可能是有用的

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

+0

非常感謝!我也要看一下MSDN文檔。 – Apache81

0

depthArrayRowIndex將基本上是您的(並行)outer for循環的索引變量/值。它會從0包容height獨家去:

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

一點解釋(C#):平行的整個第三個論據是lambda函數,該操作將獲得一個Int32參數,它發生成爲循環索引。

所以我認爲你的C++翻譯應該開始爲: concurrency::parallel_for(0, height, ...而不是width

+0

哦,是的,你是對的!非常感謝你的亮點:-) – Apache81

0
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 
} 

assming Fooint類型。在C++中,單行lambdas可以跳過->Bar部分。不返回任何東西的Lambdas可以跳過->void

可以列出拍攝參數(如果他們是按值或引用捕獲)的C++拉姆達的[]內,但C#lambda表達式做捕捉由智能參考隱含地使用一切的等價物。如果您的lambda的生存期限制在創建C++ lambda的範圍內,則[&]是等效的。

如果它可以持續更長時間,那麼您需要處理lambda捕獲的數據的生命週期管理,並且您希望更謹慎並且只能按值捕獲(並且可能在捕獲之前將數據打包到shared_ptrshared_ptr)。

+0

是的。 *按價值*非常重要! –