Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Making Managed Extensions for C++ STL friendly

0.00/5 (No votes)
17 Apr 2003 1  
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 version gc version Implemented in terms of
equal_to gc_equal_to System::Object::Equals
not_equal_to gc_not_equal_to System::Object::Equals
less gc_less System::IComparable::CompareTo
greater gc_greater System::IComparable::CompareTo
less_equal gc_less_equal System::IComparable::CompareTo
greater_equal gc_greater_equal System::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() const Number of the elements
bool empty() const Is the collection empty?
operator Container() const Conversion to the wrapped container type
Container operator->() const Enables 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 has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here