Click here to Skip to main content
15,886,362 members
Articles / Programming Languages / C++/CLI
Article

Making Managed Extensions for C++ STL friendly

Rate me:
Please Sign up or sign in to vote.
4.89/5 (19 votes)
17 Apr 2003BSD5 min read 185.6K   925   31   36
Some code to help you combine MC++ and STL

Introduction

Choosing the right programming language for .NET is mostly a matter of personal preference and the problem that needs to be solved. For me, one of the most important reasons to use managed extensions for C++ (MC++) is the possibility to reuse "native" C++ code, especially C++ Standard Library.

In the October 2002 edition of C/C++ User Journal, there is an article by Jonathan Caves, that describes some issues with using C++ Standard Library with managed types. My aim is to go one step further and offer some code that will help developers to easily integrate managed types and STL. This code is contained in a single header file gcstl.h.

To use the code I provided here, you will need working knowledge of Managed Extensions for C++ and STL. That assumes that, at least you have read Managed Extensions for C++ Specification and some introductionary STL text. To really understand what is going on under the hood, you will need to be familiar with STL internals, and to have a good understanding of CLR and .NET Framework.

What is the problem?

To illustrate the problems with working with managed types and STL, try to compile the next piece of code:

#using <mscorlib.dll>
#include <vector>
#include <algorithm>
#include <iterator>
#include <iostream>

using namespace System;
using namespace std;

int main()
{
    vector <String __gc*> v; //Problem 1
    v.push_back(S"bca");
    v.push_back(S"bac");
    v.push_back(S"abc");

    sort (v.begin(), v.end()); //Problem 2

    copy (v.begin(), v.end(), ostream_iterator<String __gc*>(wcout, L" ")); 
    //Problem 3
}

Also, it would be nice if we could use STL algorithms with .NET collections. Something like:

String __gc* st_array[] = {S"bca", S"bac", S"abc"};
std::find(st_array[0], st_array[3], S"abc"); //Problem 4

The code above has following problems:

  1. Unmanaged classes cannot contain __gc pointers.
  2. Built in comparison operators can not be used to sort managed objects.
  3. C++ output streams don't work with managed types, and therefore we can not use ostream_iterator.
  4. Standard algorithms don't work with .NET collections.

Let's discuss each of those problems separately.

Problem 1: Storing __gc Pointers in STL Containers

As explained in Managed Extensions for C++ Specification, chapter 16.3 "It is illegal to declare a member of an unmanaged class to have __gc pointer type.". However, there is the class System::Runtime::InteropServices::GCHandle that enables to reference a managed object from unmanaged heap. Even better, good people from VC.NET team have made a wrapper template gcroot to make working with GCHandle easy. Just include vcclr.h and use it like this:

#using <mscorlib.dll>
#include <vector>
#include <algorithm>
#include <iterator>
#include <iostream>
#include <vcclr.h>

using namespace System;
using namespace std;

int main()
{
    //vector <String __gc*> v; //Problem 1
    vector <gcroot<String __gc*> > v;

    v.push_back(S"bca");
    v.push_back(S"bac");
    v.push_back(S"abc");

    /*
    sort (v.begin(), v.end()); //Problem 2

    copy (v.begin(), v.end(), ostream_iterator<String __gc*>(wcout, S" ")); 
    //Problem 3
    */
}

To find out about internals of gcroot, take a look at the header file gcroot.h.

Problem 2: Comparisons of Managed Objects

To work with STL algorithms, as well as with sorted containers, you must be able to compare the values of your objects. STL heavily relies on value semantics, and it is generally recommended to avoid pointers (__gc as well as __nogc) in general, but it is possible to work easily with managed objects by using some function objects, that I provide in the header file gcstl.h:

#using <mscorlib.dll>
#include <vector>
#include <algorithm>
#include <iterator>
#include <iostream>
#include "gcstl.h"

using namespace System;
using namespace std;

int main()
    {
    //vector <String __gc*> v; //Problem 1
    vector <gcroot<String __gc*> > v;

    v.push_back(S"bca");
    v.push_back(S"bac");
    v.push_back(S"abc");

    
    //sort (v.begin(), v.end()); //Problem 2
    sort (v.begin(), v.end(), gc_less<String __gc*>());

    /*
    copy (v.begin(), v.end(), ostream_iterator<String __gc*>(wcout, S" ")); 
    //Problem 3
    */
}

Note that, we now use the version of sort, which uses a user-defined predicate function object that defines the comparison criterion. Most STL algorithms have versions that enable users to provide comparison predicates.

In the header file gcstl.h, I define comparison function objects that work with __gc pointers and correspond to the ones defined in the standard header <functional>. Be sure to use those function objects with algorithms, as well as with sorted containers like set and map:

set<gcroot<String __gc*>, gc_less<String __gc*>()> my_set;

rather than:

set<gcroot<String __gc*> > my_set;

Actually, both versions will compile, but in the later case ordering will be meaningless.

Function objects defined in gcstl.h are listed in the following table:

std versiongc versionImplemented in terms of
equal_togc_equal_toSystem::Object::Equals
not_equal_togc_not_equal_toSystem::Object::Equals
lessgc_lessSystem::IComparable::CompareTo
greatergc_greaterSystem::IComparable::CompareTo
less_equalgc_less_equalSystem::IComparable::CompareTo
greater_equalgc_greater_equalSystem::IComparable::CompareTo

From the table, you can see that for a managed type to work with less, greater, less_equal and greater_equal, it must implement IComparable interface.

Problem 3: Replacement for ostream_iterator

I often use ostring_stream to dump the content of my STL containers either to screen or to a file. Therefore, I thought it would be nice to have an output iterator with similar semantics, that will internally work with .NET System::IO::TextWriter. So I made textwriter_iterator. Here it is:

#include <vector>
#include <algorithm>
#include <iterator>
#include "gcstl.h"

using namespace System;
using namespace std;

int main()
{
    //vector <String __gc*> v; //Problem 1
    vector <gcroot<String __gc*> > v;

    v.push_back(S"bca");
    v.push_back(S"bac");
    v.push_back(S"abc");
    
    //sort (v.begin(), v.end()); //Problem 2
    sort (v.begin(), v.end(), gc_less<String __gc*>());
    
    //copy (v.begin(), v.end(), 
    //ostream_iterator<String __gc*>(wcout, S" ")); 
    //Problem 3
    copy (v.begin(), v.end(), textwriter_iterator<String __gc*>
                                                (Console::Out, S" "));    
}

Internally, textwriter_iterator uses Object::ToString() to write an object to a text writer.

Notice that I didn't provide a managed counterpart for istream_operator. The reason for that is that, in my C++ programming I have not find this operator that useful, and since the implementation would not be trivial, I decided to skip it.

Problem 4: Using STL algorithms with .NET collections

To make STL algorithms work with .NET collections, I created a template wrapper gc_collection. Here is an example how to work with this wrapper:

#include <algorithm>
#include "gcstl.h"

using namespace System;
using namespace std;


int main()
    {
    String __gc* st_array[] = {S"bca", S"bac", S"abc"};
    gc_collection<Array __gc*, String __gc*> cont(st_array);
    gc_collection<Array __gc*, String __gc*>::const_iterator it =
        find_if(cont.begin(), cont.end(),
            bind2nd(gc_equal_to<gcroot<String __gc*> >(),S"abc"));
    if (it != cont.end())
        Console::WriteLine(*it);
}

gc_collection has two template parameters: Container (by default it is System::Collections::ICollection __gc*) - the type of the wrapped container; Elem (by default System::Object __gc*) - the type of contained elements.

I designed gc_collection to cover a broad range of .NET collections, rather than to have many features. Therefore, it was implemented in terms of ICollection interface, and not IList or IDictionary. I plan to make wrappers for these interfaces in the next release of gcstl.h.

gc_collection has the following member functions:

gc_collection (Container container)Constructor
const_iterator begin()The first element
const_iterator end()Past-the-end element
int size() constNumber of the elements
bool empty() constIs the collection empty?
operator Container() constConversion to the wrapped container type
Container operator->() constEnables to use gc_collection as a smart pointer

gc_collection::const_iterator is not even a forward immutable iterator - it lacks post-increment operator. It is implemented in terms of IEnumerator interface.

Minimalist as is, gc_collection gives us possibility to work with most non-mutating STL algorithms.

References

  1. Managed Extensions for C++ Specification
  2. Jonathan Caves: Using the C++ Standard Library with Managed Types - C/C++ Users Journal, October 2002.

License

This article, along with any associated source code and files, is licensed under The BSD License


Written By
Software Developer (Senior)
United States United States
Born in Kragujevac, Serbia. Now lives in Boston area with his wife and daughters.

Wrote his first program at the age of 13 on a Sinclair Spectrum, became a professional software developer after he graduated.

Very passionate about programming and software development in general.

Comments and Discussions

 
Generalefficiency question Pin
Gammill17-Oct-04 18:44
Gammill17-Oct-04 18:44 
GeneralRe: efficiency question Pin
Nemanja Trifunovic18-Oct-04 2:49
Nemanja Trifunovic18-Oct-04 2:49 
GeneralRe: efficiency question Pin
juno7124-Mar-05 19:43
juno7124-Mar-05 19:43 
GeneralCan't compile in Form1.h Pin
Gammill17-Oct-04 18:37
Gammill17-Oct-04 18:37 
GeneralRe: Can't compile in Form1.h Pin
Nemanja Trifunovic18-Oct-04 2:52
Nemanja Trifunovic18-Oct-04 2:52 
Generalthis is great Pin
Vadim Tabakman29-Jun-04 13:55
Vadim Tabakman29-Jun-04 13:55 
GeneralRe: this is great Pin
Nemanja Trifunovic30-Jun-04 2:13
Nemanja Trifunovic30-Jun-04 2:13 
GeneralPassing vector from MC++ byvalue and byref Pin
Sabir28-Jun-04 1:30
Sabir28-Jun-04 1:30 
GeneralRe: Passing vector from MC++ byvalue and byref Pin
Nemanja Trifunovic29-Jun-04 3:32
Nemanja Trifunovic29-Jun-04 3:32 
GeneralRe: Passing vector from MC++ byvalue and byref Pin
Sabir30-Jun-04 0:01
Sabir30-Jun-04 0:01 
GeneralRe: Passing vector from MC++ byvalue and byref Pin
Nemanja Trifunovic30-Jun-04 2:19
Nemanja Trifunovic30-Jun-04 2:19 
GeneralRe: Passing vector from MC++ byvalue and byref Pin
Sabir30-Jun-04 19:31
Sabir30-Jun-04 19:31 
GeneralRe: Passing vector from MC++ byvalue and byref Pin
Nemanja Trifunovic1-Jul-04 2:35
Nemanja Trifunovic1-Jul-04 2:35 
GeneralRe: Passing vector from MC++ byvalue and byref Pin
Sabir1-Jul-04 18:43
Sabir1-Jul-04 18:43 
GeneralRe: Passing vector from MC++ byvalue and byref Pin
Sabir30-Jun-04 19:36
Sabir30-Jun-04 19:36 
Generalmanaged strings Pin
C LaMorticella16-Apr-04 3:50
C LaMorticella16-Apr-04 3:50 
GeneralRe: managed strings Pin
Nemanja Trifunovic16-Apr-04 4:56
Nemanja Trifunovic16-Apr-04 4:56 
GeneralSTL map with managed extensions Pin
bollwerj15-Jan-04 2:29
bollwerj15-Jan-04 2:29 
GeneralRe: STL map with managed extensions Pin
Nemanja Trifunovic15-Jan-04 5:23
Nemanja Trifunovic15-Jan-04 5:23 
GeneralRe: STL map with managed extensions Pin
bollwerj15-Jan-04 6:25
bollwerj15-Jan-04 6:25 
GeneralRe: STL map with managed extensions Pin
bollwerj15-Jan-04 7:11
bollwerj15-Jan-04 7:11 
GeneralRe: STL map with managed extensions Pin
Nemanja Trifunovic15-Jan-04 9:01
Nemanja Trifunovic15-Jan-04 9:01 
GeneralRe: STL map with managed extensions Pin
bollwerj16-Jan-04 3:15
bollwerj16-Jan-04 3:15 
GeneralRe: STL map with managed extensions Pin
bollwerj20-Jan-04 9:40
bollwerj20-Jan-04 9:40 
Things seemed to be going smoothly until I attempted to access an object stored in a multimap using "find". Here's what is happening:

The multimap and iterator declaration:
multimap<double, gcroot<CGeo __gc*>, less < double > > mapLat;
multimap<double, gcroot<CGeo __gc*>, less < double > >::iterator latIt;

where CGeo is a public __gc class

I load the map with:
mapLat.insert(make_pair(double(lat), gcroot<CGeo __gc*>(geo)));

mapLat.size() returnes 6268 entries.

The value -8.702569 is one of the keys (first)

If I do the following:
double search = -8.702569;
latIt = mapLat.find(search);

and try:
double myFirst = latIt->first;
or
double mySeconf = latIt->second->lat;

I get an unhandled exception even though I'm in a try...catch block Cry | :((

However, I can set latIt = mapLat.begin(); and iterate through the table OK, eventually locating the key and its second.

It seems that "find" is not returning a good iterator but I don't understand enough to figure out why. Hopefully you will be good enough to help again.

Thanks

John
GeneralRe: STL map with managed extensions Pin
Nemanja Trifunovic20-Jan-04 12:16
Nemanja Trifunovic20-Jan-04 12:16 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.