Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

list

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 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!

like image 424
developer Avatar asked Jul 20 '11 14:07

developer


3 Answers

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

like image 160
Djole Avatar answered Nov 19 '22 17:11

Djole


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.

like image 2
Ajay Avatar answered Nov 19 '22 19:11

Ajay


If you don't need a managed container, you can use the native list type:

#include <list>

std::list<MyCppObject*> mylist;
// ...
mylist.remove(mycppobjptr);
like image 1
Ben Straub Avatar answered Nov 19 '22 17:11

Ben Straub