views:

56

answers:

2

Hi,

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  A: 

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;
}
ngoozeff
That works perfectly. thanks a lot
ChRtS
A: 

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.

Ben Voigt
I wanted to use a multimap in fact. A dictionnary can only direct one key to one value right?
ChRtS
in that scenario I usually use a `Dictionary<TKey, List<TValue>>`.
Ben Voigt