问题
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