开发者

Creating some sort of list of C++ objects in C++/CLI

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开发者_StackOverflow社区 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);


try

single object
MyCppObject^ _myCppObject = gcnew MyCppObject();

list of objects
List< MyCppObject ^>^ LIST = gcnew List< MyCppObject >();

add single element
LIST->Add( _myCppObject );

// remove single element
LIST->Remove( _myCppObject );

// these are all managed objects so when loss of scope it self destructs

// although such might be the case as per System::GC, you may still do...

LIST->Clear();

delete LIST;

LIST = nullptr;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜