Click here to Skip to main content
15,886,680 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

 
GeneralRe: STL map with managed extensions Pin
bollwerj21-Jan-04 2:51
bollwerj21-Jan-04 2:51 
GeneralRe: STL map with managed extensions Pin
Nemanja Trifunovic21-Jan-04 5:31
Nemanja Trifunovic21-Jan-04 5:31 
GeneralRe: STL map with managed extensions Pin
bollwerj21-Jan-04 5:57
bollwerj21-Jan-04 5:57 
GeneralRe: STL map with managed extensions Pin
Nemanja Trifunovic21-Jan-04 6:23
Nemanja Trifunovic21-Jan-04 6:23 
GeneralRe: STL map with managed extensions Pin
bollwerj21-Jan-04 8:26
bollwerj21-Jan-04 8:26 
GeneralRe: STL map with managed extensions Pin
Philippe Mori18-Jun-04 3:42
Philippe Mori18-Jun-04 3:42 
GeneralRe: STL map with managed extensions [modified] Pin
Alexander Zabluda26-Aug-07 1:33
Alexander Zabluda26-Aug-07 1:33 
Generaloperator++(int) Pin
Alexei Zakharov21-Apr-03 20:23
Alexei Zakharov21-Apr-03 20:23 
GeneralRe: operator++(int) Pin
Nemanja Trifunovic22-Apr-03 5:40
Nemanja Trifunovic22-Apr-03 5:40 
GeneralNice job but.. Pin
Rama Krishna Vavilala18-Apr-03 15:04
Rama Krishna Vavilala18-Apr-03 15:04 
GeneralRe: Nice job but.. Pin
Nemanja Trifunovic21-Apr-03 5:12
Nemanja Trifunovic21-Apr-03 5:12 

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.