I am trying to create a list/collection of C++ objects in C++/CLI and I have tried various ways but nothing seems to work (errors at compile time).
I have tried:
List<MyCppObject*> ^myList; //Does not allow non-.NET objects
ArrayList ^myList;
...
myList->Remove(myCppObject); //cannot convert parameter 1 from 'MyCppObject *' to 'System::Object ^'
My requirements:
1) The list MUST contain C++ objects
2) I need the ability to remove a particular object (e.g. vector won't work because it's only push/pop off top)
Question: How can I make a list/collection of C++ objects in a C++/CLI function work with the ability to easily remove a particular object?
Let me know if anyone would like some additional info; thanks in advance for your help!
Its either System::IntPtr to unmanaged objects as in List<System::IntPtr>^ or std::list (or your own c++ list) and then wrapper around that
EDIT:
You could do it like this
MyCppObject mynativeobj[10];
System::Collections::Generic::List<System::IntPtr>^ mlist = gcnew System::Collections::Generic::List<System::IntPtr>();
for(int i =0;i<10;i++)
{
mlist->Add(System::IntPtr((void*)&mynativeobj[i]));
}
The only problem is that all the memory will still reside in the unmanaged part so if your vars go out of scope the IntPtrs won't be valid anymore. Also you need to free the memory under the pointers yourself
To store native objects/pointers you must use native collection classes. If you want the collection class to maintain allocation/deallocation use <MyCppObject>, or use <MyCppObject*> if you would maintain the memory allocation (i.e. collection class would hold the pointers only).
STL/CLR classes would do something opposite - you can use STL classes for storing .NET objects.
If you don't need a managed container, you can use the native list type:
#include <list>
std::list<MyCppObject*> mylist;
// ...
mylist.remove(mycppobjptr);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With