问题
I guess it's kind of a stupid question but here is my problem :
I want to have a hash_map<int, Object^>
as an attribute of my object BigObject
, which is written in managed C++.
So I have to declare a pointer, hash_map<int, Object^>* hash
because I cannot declare explicitely native object in managed code.
How can I insert an object ? the hash_map[]
won't work with a pointer, and I cannot make insert work (I cannot use a std::pair<int, Object^>
because Object is managed...
Thanks a lot
回答1:
You should declare your hashmap as hash_map<int, gcroot<Object^> >
. You will need to #include <vcclr.h>
See also msdn
edit: added code sample
#include <iostream>
#include <vcclr.h>
#include <hash_map>
using namespace std;
using namespace stdext;
using namespace System;
int main()
{
hash_map<int, gcroot<Object^> > hash;
hash.insert( make_pair<int, gcroot<Object^> >( 5,
gcnew String("hello world") ) );
return 0;
}
回答2:
If you're working in .NET, why not use one of the .NET collections? They are directly usable in C++/CLI, and can also be shared with other .NET languages, which a std::hash_map
cannot. And they play nicely with the garbage collector.
.NET provides several hashtable implementations, including 'System.Collections.HashTable' and System.Collections.Generic.Dictionary.
In your case, a Dictionary<int, Object^>^
would be appropriate.
回答3:
hash_map <double,gcroot<siteNEVObjectdic^>> d;
d.insert(make_pair<double,gcroot<siteNEVObjectdic^>>(PN2,gcnew siteNEVObjectdic(Lat1,Long1,Lat2,Long2,Lat3,Long3)));
this worked as a charm.
来源:https://stackoverflow.com/questions/3373012/hashmap-dealing-with-managed-objects-c