HashMap : Dealing with Managed objects C++

*爱你&永不变心* 提交于 2019-12-14 03:15:18

问题


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

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