Managed C++Managed C++ doesn't really represent a separate programming language. A number of features introduced by the .NET Framework aren't supported through the standard C++ programming language, Visual C++ 2003, also better known as Managed C++. Managed C++ extensions represent an additional set of keywords that provide the necessary extensions to C++ for development of .NET constructs. Called a power-oriented programming language, Visual C++ .NET provides .NET application developers the ultimate combination of power, control, and performance-centric bridging of the native and managed code environments. Key highlights of the Visual C++ .NET programming language include
Hello World#using <mscorlib.dll> using namespace System; void main() { Console::WriteLine(S"Hello World in Managed C++"); } Compiling a Managed Extensions “enabled C++ program requires using the /CLR compiler option, which indicates to the compiler that the C++ programs must be compiled into a .NET assembly. cl /CLR HelloWorld.cpp Managed ExtensionsTable 3.4 provides a quick list of key managed extensions to the C++ programming language. Table 3.4. Key Managed C++ Extension Keywords
To create a managed class (which means that no allocation is required), prefix the __gc keyword to a C++ class definition. This indicates to the C++ compiler that what is going to be declared is a managed C++ class (Listing 3.23). Listing 3.23 Creating Managed Classes (Managed C++)#using <mscorlib.dll> namespace hks { __gc class Person { public: System::String* FirstName; System::String* LastName; Person(System::String* FirstName, System::String* LastName) { this->FirstName = FirstName; this->LastName = LastName; } }; }; void main() { hks::Person* p1 = new hks::Person(S"Hitesh",S"Seth"); hks::Person* p2 = p1; p1->FirstName = S"John"; p2->LastName = S"Doe"; System::Console::WriteLine("{0}.{1}",p1->FirstName,p1->LastName); System::Console::WriteLine("{0}.{1}",p2->FirstName,p2->LastName); } Listing 3.24 is another example of using managed extensions, this time to create events and delegates. Listing 3.24 Using Events and Delegates Managed Extensions (Managed C++)#using <mscorlib.dll> namespace hks { __delegate void MyDelegate(System::String *msg); __gc class HelloWorld { public: void PrintOnce(System::String *msg) { System::Console::WriteLine(msg); } void PrintTwice(System::String *msg) { System::Console::WriteLine("1.{0}",msg); System::Console::WriteLine("2.{0}",msg); } }; }; int main() { hks::HelloWorld* hw = new hks::HelloWorld(); System::String *msg = S"Hello Delegates"; hks::MyDelegate *d1 = new hks::MyDelegate(hw,&hks::HelloWorld::PrintOnce); hks::MyDelegate *d2 = new hks::MyDelegate(hw,&hks::HelloWorld::PrintTwice); d1->Invoke(msg); d2->Invoke(msg); } |