在c++ /CLI中创建c++对象列表
Creating some sort of list of C++ objects in C++/CLI
我试图在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;
相关文章:
- 什么时候调用组成单元对象的析构函数
- 对RValue对象调用的LValue ref限定成员函数
- CMake-按正确顺序将项目与C运行时对象文件链接
- 空基优化子对象的地址
- 将对象数组的引用传递给函数
- 你能重载对象变量名本身返回的内容吗
- C++使用整数的压缩数组初始化对象
- 找不到成员对象:没有名为get_event()的成员,也处理多态性和向量
- 将对象移动到std::shared_ptr
- 代理对象的常量正确性
- 提升 ASIO 无法识别计时器对象
- 将Ref对象作为类成员
- 将包含C样式数组的对象初始化为成员变量(C++)
- 如何返回一个类的两个对象相加的结果
- 使用std::函数映射对象方法
- 是否需要删除包含对象的"pair"?
- 如何在自删除后将对象设置为nullptr
- 迭代时从向量和内存中删除对象
- 构造对象的歧义
- 使用"std::unordereded_map"映射到"std::list"对象