Cpp/Cli Convert std::map to .net dictionary

我怕爱的太早我们不能终老 提交于 2019-12-13 19:43:15

问题


I have a cpp project, a cpp cli project and a c# win forms project. I have a std::map in my native cpp project. How can i convert it to .net dictonary in my cli project?


回答1:


//Assuming dictionary of int/int:
#include <map>

#pragma managed

using namespace System::Collections::Generic;
using namespace std;

/// <summary>
/// Converts an STL int map keyed on ints to a Dictionary.
/// </summary>
/// <param name="myMap">Pointer to STL map.</param>
/// <returns>Dictionary of int keyed by an int.</returns>
/// <exception cref="ArgumentNullException">The <paramref name="myMap"/> parameter was a NULL pointer.    
Dictionary<int, int>^ Convert(map<int, int>* myMap)
{ 
  if (!myMap)
    throw gcnew System::ArgumentNullException("myMap");

  Dictionary<int, int>^ h_result = gcnew Dictionary<int, int>(myMap->size());

  for (pair<int, int> kvp : *myMap)
  {
     h_result->Add(kvp.first, kvp.second);
  }

  return h_result;
}


来源:https://stackoverflow.com/questions/9920933/cpp-cli-convert-stdmap-to-net-dictionary

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!