Click here to Skip to main content
Click here to Skip to main content

Making Managed Extensions for C++ STL friendly

By , 17 Apr 2003
Rate this:
Please Sign up or sign in to vote.

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, along with any associated source code and files, is licensed under The BSD License

About the Author

Nemanja Trifunovic
Software Developer (Senior) SAP
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 PinmemberGammill17-Oct-04 18:44 
GeneralRe: efficiency question PinmemberNemanja Trifunovic18-Oct-04 2:49 
GeneralRe: efficiency question Pinmemberjuno7124-Mar-05 19:43 
GeneralCan't compile in Form1.h PinmemberGammill17-Oct-04 18:37 
GeneralRe: Can't compile in Form1.h PinmemberNemanja Trifunovic18-Oct-04 2:52 
Generalthis is great PinmemberJubjub29-Jun-04 13:55 
GeneralRe: this is great PinmemberNemanja Trifunovic30-Jun-04 2:13 
GeneralPassing vector from MC++ byvalue and byref PinmemberSabir28-Jun-04 1:30 
GeneralRe: Passing vector from MC++ byvalue and byref PinmemberNemanja Trifunovic29-Jun-04 3:32 
GeneralRe: Passing vector from MC++ byvalue and byref PinmemberSabir30-Jun-04 0:01 
GeneralRe: Passing vector from MC++ byvalue and byref PinmemberNemanja Trifunovic30-Jun-04 2:19 
GeneralRe: Passing vector from MC++ byvalue and byref PinmemberSabir30-Jun-04 19:31 
GeneralRe: Passing vector from MC++ byvalue and byref PinmemberNemanja Trifunovic1-Jul-04 2:35 
GeneralRe: Passing vector from MC++ byvalue and byref PinmemberSabir1-Jul-04 18:43 
GeneralRe: Passing vector from MC++ byvalue and byref PinmemberSabir30-Jun-04 19:36 
Generalmanaged strings PinsussChris LaMorticella16-Apr-04 3:50 
GeneralRe: managed strings PinmemberNemanja Trifunovic16-Apr-04 4:56 
GeneralSTL map with managed extensions Pinmemberbollwerj15-Jan-04 2:29 
GeneralRe: STL map with managed extensions PinmemberNemanja Trifunovic15-Jan-04 5:23 
GeneralRe: STL map with managed extensions Pinmemberbollwerj15-Jan-04 6:25 
GeneralRe: STL map with managed extensions Pinmemberbollwerj15-Jan-04 7:11 
GeneralRe: STL map with managed extensions PinmemberNemanja Trifunovic15-Jan-04 9:01 
GeneralRe: STL map with managed extensions Pinmemberbollwerj16-Jan-04 3:15 
GeneralRe: STL map with managed extensions Pinmemberbollwerj20-Jan-04 9:40 
GeneralRe: STL map with managed extensions PinmemberNemanja Trifunovic20-Jan-04 12:16 

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

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

| Advertise | Privacy | Mobile
Web01 | 2.8.140415.2 | Last Updated 18 Apr 2003
Article Copyright 2003 by Nemanja Trifunovic
Everything else Copyright © CodeProject, 1999-2014
Terms of Use
Layout: fixed | fluid