Click here to Skip to main content
11,716,249 members (89,524 online)
Click here to Skip to main content

Introduction to Managed C++

, 7 Jul 2002 257.2K 1.3K 48
Rate this:
Please Sign up or sign in to vote.
An attempt to get a beginner started on Managed C++

Introduction

This is intended as a jump-start tutorial for Managed C++ programming. It does not cover every aspect of the managed extensions, but it does cover certain areas that are often puzzling to someone coming from a C# or a native C++ background. The article assumes that the reader is familiar with the basic elements of .NET technology and that the user can understand C++ code when he or she sees it.

Simple program

#using <mscorlib.dll>
 
using namespace System;

int _tmain(void)
{
    return 0;
}

#using is a preprocessor directive that imports meta data from a .NET module or library. In our small program we have used #using on mscorlib.dll which is an essential library for all .NET programs. Just using #using gives us access to all the namespaces and classes in that module or library. But we'd have to type the fully qualified name for each class we use, including the namespace or namespaces if any. We can use the using namespace directive which will allow us to use class names without having to use the namespace-name explicitly.

For example I can write this :-

System::Console::WriteLine("Hello Earth");

But if I have used a using namespace directive, then I can use :-

using namespace System;
...
Console::WriteLine("Hello Earth");

It's mostly a matter of readability. Some people might prefer to use fully qualified names to improve the clarity of their code. And sometimes you are forced to, as when two namespaces have classes with the same names in which case the compiler gets confused.

Managed classes

A managed class is a class that is garbage collected, means you don't have to delete it after using it. All that's managed for you by the common language runtime. In MC++ we create managed classes using the __gc keyword as shown below.

__gc class First
{
public:
    First()
    {
        m_name = "Anonymous";
    }
    First(String* s)
    {
        m_name = s;
    }
    String* GetName()
    {
        return m_name;
    }
    void SetName(String* s)
    {
        m_name = s;
    }
private:
    String* m_name;
};

Well, it looks more or less like a normal C++ class except that we have used the __gc keyword when declaring it. That marks it as managed. You'll also notice how I have used String* instead of String. This is because the String class is a managed class that can only be declared on the heap.

First* f1 = new First();
First* f2 = new First("Andrew");
Console::WriteLine(f1->GetName());
Console::WriteLine(f2->GetName());
f2->SetName("Peace");
Console::WriteLine(f2->GetName());

Using the managed class is not dissimilar from using a normal old-style C++ class. Except that I cannot declare objects of type First, I have to declare them on the heap using First* and new. As you might observe, I have not called delete. Hey, don't look at me with that sort of gleam in your eyes as if to tell me that I should not be so careless. I didn't call delete because it's not required that I do so. This is Managed C++ we are talking about, remember. And because First is a managed class, the common language runtime will automatically delete the objects that are no longer under use, using it's garbage collector. Very handy, I say very handy!

Using properties

Take a look at the two listings below :-

//Listing A
f2->SetName("Peace");
Console::WriteLine(f2->GetName());
//Listing B
f2->Name = "Colin";
Console::WriteLine(f2->Name);

Obviously the second listing is more readable. Of course using a public member variable would be a very impetuous idea and one that would result in a lot of scornful looks from most programmers. But in .NET we have properties, in fact I have some rather vague ideas that the native C++ compiler supports properties too, but since the vagueness is rather strong, I better keep quiet about that one.

__gc class First
{
public:

...

    __property String* get_Name()
    {
        return m_name;
    }
    __property void set_Name(String* s)
    {
        m_name = s;
    }

...

};

If you have only a get_ function then your property is read-only. If you have only the set_ function you have a write-only property. And in our case, since we have both get_ and set_ functions, we have a read-and-write property. The get_ function's return type must be same as the set_ function's argument. MSDN adds that you cannot define a property that has the same name as the containing class.

Boxing

Consider the function below :-

void Show(Object* o)
{
    Console::WriteLine(o);
}

Rather neat, eh? It takes an object of type Object and displays it on the console. Now see this snippet of code.

String* s1 = "Hello World";
Show(s1);

Compiles and works fine. Now see the following snippet of code.

int i = 100;
Show(i); //This won't compile

Blast! That won't even compile. You'll get compiler error C2664: 'Show' : cannot convert parameter 1 from 'int' to 'System::Object __gc *'. This is where we need to use the __box keyword.

int i = 100;
Show(__box(i));

What __box does is simple. It creates a new managed object on the heap and copies the value type object into the managed object. And it returns the managed object which is actually a copy of the original value type object. This means that if you modify the managed object returned by an__box, the original object won't change at all.

Unboxing

Obviously if you can box, you should be able to unbox too, eh? Let's say we want to box a value object to an Object and then unbox it back to a value object. The following code snippet shows you how to accomplish this chore.

Object* o1 = __box(i);
int j = *static_cast<__box int*>(o1);
j *= 3;
Show(__box(j));

Good heavens! That turned out to be rather more sinister looking than you had expected I bet. What we do is to cast the managed object to the __gc pointer on the CLR heap and then we simply dereference it. You can use dynamic_cast instead of static_cast for increased type-safety.

Native code blocks

Consider the following function.

void NativeCall()
{
    puts("This is printed from a native function");
}

As you can see, it uses purely normal non-.NET stuff. Obviously we can improve execution speed if we can compile this function as native. MC++ provides us with the #pragma managed and #pragma unmanaged preprocessor directives. We simply add a #pragma unmanaged just before the function and then add a #pragma managed just after the function.

#pragma unmanaged
 
void NativeCall()
{
    ...
}

#pragma managed 

Now when this function is encountered during program execution, the common language runtime will pass on control to the native platform. Obviously we must use this whenever we have functions that use fully unmanaged functions. What's real neat is that we call call unmanaged functions that are marked as #pragma unmanaged from within managed blocks of code.

__value classes

Earlier I had said that managed classes cannot be allocated on the stack. Sometimes, we might have the requirement for a very simple class, often merely for storing some values. In such cases it might be desirable to have a value type class that can be allocated on the stack. That's where the __value keyword comes in. The following code snippet shows you how to declare a value type class.

__value class Second
{
public:
    void Abc()
    {
        Console::WriteLine("Second::Abc");
    }
};

Now we can declare objects of type Second on the stack.

Second sec;
sec.Abc();

In fact we can even declare them on the heap. But remember this won't be the CLR managed heap and thus we need to delete our objects on our own.

Second* psec = __nogc new Second();
psec->Abc();
delete psec;

More reading

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

Share

About the Author

Nish Nishant
United States United States
Nish Nishant is a Software Architect/Consultant based out of Columbus, Ohio. He has over 15 years of software industry experience in various roles including Lead Software Architect, Principal Software Engineer, and Product Manager. Nish is a recipient of the annual Microsoft Visual C++ MVP Award since 2002 (13 consecutive awards as of 2014).

Nish is an industry acknowledged expert in the Microsoft technology stack. He authored
C++/CLI in Action for Manning Publications in 2005, and had previously co-authored
Extending MFC Applications with the .NET Framework for Addison Wesley in 2003. In addition, he has over 140 published technology articles on CodeProject.com and another 250+ blog articles on his
WordPress blog. Nish is vastly experienced in team management, mentoring teams, and directing all stages of software development.

Contact Nish : You can reach Nish on his google email id voidnish.

Website and Blog

You may also be interested in...

Comments and Discussions

 
QuestionWhy slowdown operation!? Pin
murti3866-Feb-07 7:19
membermurti3866-Feb-07 7:19 
personally i was always disagreed with use in any .net code, or just extensions that's used personally.It is not against microsoft stuff, but also against companies that tries put a spell on industry, win money with it by wasting smart, effective coders with their stupid extensions.As example, if there's a arctangent usage of c++, why anyone stupid should try .net to decrease speed such a slow operation?Many of below are tried to say, "we are up to goods" but they don't want to waste to enter a company profile, just any good programmer should be.
I see that microsoft wasting too much money to convert programmers to their position.Well, almost everyone forgot about raw sockets, assembly code, os api and so on.So is it the point to make 3 years old children write their programs in slowest way?
c and c++ are mostly designed for processor power and allows with its libraries mostly used atomic operations can be done easily like pow(x,y).thats why it doesn't have any windowing library by standart.But if there wasn't any libraries, would microsoft, or other one try to sell basics for a price?
If this things make ease of programming,why don't we just make a smart software that itself generate modules, that's very slow and can generate any software desired?
I always enjoy articles.But it is mostly explains .NET and no more deep about other things.I think .NET is easy, why is there so many articles?

"As far as the laws of mathematics refer to reality, they are not
certain; and as far as they are certain, they do not refer to reality." Albert Einstein

GeneralManaging MFC Pin
MohitJn8-Mar-04 22:00
memberMohitJn8-Mar-04 22:00 
GeneralPlatform SDK with Unmanaged interface Pin
PawanKishore20-Feb-04 20:09
memberPawanKishore20-Feb-04 20:09 
GeneralManaged C++ classes Pin
ricky_casson9-Jan-04 12:37
memberricky_casson9-Jan-04 12:37 
GeneralCreating objects of unmanaged C++ in managed C++ Pin
moist10-Aug-03 20:16
membermoist10-Aug-03 20:16 
GeneralRe: Creating objects of unmanaged C++ in managed C++ Pin
Nishant S11-Aug-03 6:59
editorNishant S11-Aug-03 6:59 
GeneralRe: Creating objects of unmanaged C++ in managed C++ Pin
moist11-Aug-03 14:48
membermoist11-Aug-03 14:48 
GeneralRe: Creating objects of unmanaged C++ in managed C++ Pin
Nishant S11-Aug-03 15:32
editorNishant S11-Aug-03 15:32 
QuestionWhat about C using Unmanaged C Static Libraries ? Pin
Anonymous26-May-03 1:37
sussAnonymous26-May-03 1:37 
Generalusing Hashtable in MC++ Pin
haranath25-Apr-03 5:58
memberharanath25-Apr-03 5:58 
GeneralRe: using Hashtable in MC++ Pin
Nemanja Trifunovic25-Apr-03 6:13
memberNemanja Trifunovic25-Apr-03 6:13 
GeneralRe: using Hashtable in MC++ Pin
haranath27-Apr-03 21:57
memberharanath27-Apr-03 21:57 
GeneralRe: using Hashtable in MC++ Pin
MarkTheShark17-Feb-05 12:42
memberMarkTheShark17-Feb-05 12:42 
GeneralHello, Nishant Pin
Anthony_Yio10-Dec-02 16:52
memberAnthony_Yio10-Dec-02 16:52 
GeneralRe: Hello, Nishant Pin
Nishant S26-Dec-02 10:26
editorNishant S26-Dec-02 10:26 
GeneralBrilliant Style Pin
Yusuf Jiruwala9-Dec-02 8:23
memberYusuf Jiruwala9-Dec-02 8:23 
GeneralRe: Brilliant Style Pin
Nishant S26-Dec-02 10:25
editorNishant S26-Dec-02 10:25 
GeneralThanks Nish Pin
Paul Watson23-Jul-02 5:29
editorPaul Watson23-Jul-02 5:29 
GeneralRe: Thanks Nish Pin
Nishant S23-Jul-02 6:33
subeditorNishant S23-Jul-02 6:33 
QuestionHow slow is it? Pin
Miguel Lopes9-Jul-02 8:21
memberMiguel Lopes9-Jul-02 8:21 
AnswerRe: How slow is it? Pin
Nishant S9-Jul-02 9:06
subeditorNishant S9-Jul-02 9:06 
GeneralRe: How slow is it? Pin
pankajdaga12-Jul-02 0:25
memberpankajdaga12-Jul-02 0:25 
GeneralRe: How slow is it? Pin
Nishant S13-Jul-02 0:41
subeditorNishant S13-Jul-02 0:41 
AnswerRe: How slow is it? Pin
Nemanja Trifunovic23-Jul-02 6:09
memberNemanja Trifunovic23-Jul-02 6:09 
GeneralRe: How slow is it? Pin
Nishant S23-Jul-02 6:37
subeditorNishant S23-Jul-02 6:37 
Generalsdrs Pin
Anonymous21-Oct-01 22:38
memberAnonymous21-Oct-01 22:38 
GeneralRe: sdrs Pin
Matt Newman9-Mar-02 15:39
memberMatt Newman9-Mar-02 15:39 
GeneralEffort Pin
Nemesh Kaur19-Oct-01 0:33
memberNemesh Kaur19-Oct-01 0:33 
GeneralRe: Effort Pin
MN19-Oct-01 5:53
memberMN19-Oct-01 5:53 
GeneralRe: Effort Pin
Matt Newman9-Mar-02 15:41
memberMatt Newman9-Mar-02 15:41 
GeneralRe: Effort Pin
James T. Johnson9-Mar-02 15:50
memberJames T. Johnson9-Mar-02 15:50 
GeneralRe: Effort Pin
Nishant S8-Jul-02 12:28
subeditorNishant S8-Jul-02 12:28 
GeneralRe: Effort Pin
Nishant S8-Jul-02 12:29
subeditorNishant S8-Jul-02 12:29 
GeneralRe: Effort Pin
Matt Newman8-Jul-02 16:11
memberMatt Newman8-Jul-02 16:11 
GeneralRe: Effort Pin
Dean 'Karnatos' Michaud9-Jul-02 8:43
memberDean 'Karnatos' Michaud9-Jul-02 8:43 
GeneralRe: Effort Pin
Nishant S9-Jul-02 9:00
subeditorNishant S9-Jul-02 9:00 
GeneralRe: Effort Pin
Rama Krishna15-Jul-02 8:47
memberRama Krishna15-Jul-02 8:47 
GeneralRe: Effort Pin
Nishant S15-Jul-02 13:56
subeditorNishant S15-Jul-02 13:56 
GeneralRe: Effort Pin
RenGirion15-Jul-02 8:34
memberRenGirion15-Jul-02 8:34 
GeneralRe: Effort Pin
Nishant S15-Jul-02 13:58
subeditorNishant S15-Jul-02 13:58 
GeneralRe: Effort Pin
suchan23-Jul-02 5:49
membersuchan23-Jul-02 5:49 
General!!!!!!!!!!!!!!!! Pin
Nishant S23-Jul-02 6:35
subeditorNishant S23-Jul-02 6:35 
GeneralRe: !!!!!!!!!!!!!!!! Pin
Kapil M4-Feb-03 7:17
memberKapil M4-Feb-03 7:17 
GeneralRe: !!!!!!!!!!!!!!!! Pin
Nishant S7-Feb-03 19:29
editorNishant S7-Feb-03 19:29 
GeneralRe: Effort Pin
Joe H7-Feb-03 8:32
sussJoe H7-Feb-03 8:32 
GeneralRe: Effort Pin
Nishant S7-Feb-03 19:32
editorNishant S7-Feb-03 19:32 

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 | Terms of Use | Mobile
Web03 | 2.8.150901.1 | Last Updated 8 Jul 2002
Article Copyright 2001 by Nish Nishant
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid