在c++ /CLI中创建c++对象列表

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

本文关键字:c++ 对象 列表 创建 CLI      更新时间:2023-10-16

我试图在c++/CLI中创建c++对象的列表/集合,我尝试了各种方法,但似乎没有任何工作(编译时错误)。

I have try:

List<MyCppObject*> ^myList; //Does not allow non-.NET objects
ArrayList ^myList;
...
myList->Remove(myCppObject); //cannot convert parameter 1 from 'MyCppObject *' to 'System::Object ^'
我要求:

1)列表必须包含c++对象

2)我需要能够删除一个特定的对象(例如,向量不会工作,因为它只是推/弹出顶部)

问题:如何使c++/CLI函数中的c++对象列表/集合具有轻松删除特定对象的能力?

如果有人想要一些额外的信息,请告诉我;提前感谢您的帮助!

它要么是System::IntPtr到非托管对象,如List<System::IntPtr>^std::list(或您自己的c++列表),然后包装在

编辑:

你可以这样做

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]));
    }

唯一的问题是,所有的内存仍将驻留在非托管部分,所以如果您的变量超出范围,IntPtr将不再有效。你还需要自己释放指针下的内存

要存储本机对象/指针,必须使用本机集合类。如果你想让集合类维护内存分配/释放,使用<MyCppObject>;如果你想维护内存分配,使用<MyCppObject*>(即集合类只保存指针)。

STL/CLR类会做一些相反的事情——你可以使用STL类来存储。net对象。

如果您不需要托管容器,您可以使用本机list类型:

#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;