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

2019-08-05 18:50发布

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条回答
We Are One
2楼-- · 2019-08-05 19:41
//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;
}
查看更多
登录 后发表回答