Managed Extensions for C++: Difference between revisions

Content deleted Content added
mNo edit summary
 
(249 intermediate revisions by more than 100 users not shown)
Line 1:
{{About|Microsoft's C++ language extensions deprecated in 2004|its successor|C++/CLI}}
{{wrongtitle|title=Managed Extensions for C++}}
{{Primary sources|date=June 2018}}
'''Managed Extensions for C++''' or '''Managed C++''' is a deprecated set of language extensions for [[C++]], including grammatical and syntactic extensions, keywords and attributes, to bring the C++ syntax and language to the [[.NET Framework]]. These extensions were created by [[Microsoft]] to allow C++ code to be targeted to the Common Language Runtime (CLR) in the form of [[managed code]], as well as continue to interoperate with native code.
 
In 2004, the Managed C++ extensions were significantly revised to clarify and simplify syntax and expand functionality to include managed [[Generic programming|generics]]. These new extensions were designated [[C++/CLI]] and included in [[Microsoft Visual Studio|Microsoft Visual Studio 2005]].<ref>{{cite web|url=https://msdn.microsoft.com/en-us/library/ms379603%28VS.80%29.aspx|title=Translation Guide: Moving Your Programs from Managed Extensions for C++ to C++/CLI|date=August 2004|publisher=[[Microsoft]]|access-date=2009-11-11}}</ref> The term ''Managed C++'' and the extensions it refers to are thus deprecated and superseded by the new extensions.
== Overview ==
Managed Extensions for C++ is a set of keywords and attributes to bring the C++ syntax and language to the [[.NET Framework]]. It is commonly referred to as Managed C++.
 
== History ==
''NOTE: Managed C++ is being superceded by a new language set, designated C++/CLI, which as of early 2005, is currently in beta testing. The information provided in this article will eventually become obsolete.''
Microsoft introduced Managed Extensions for C++ in [[Microsoft Visual C++]] 2002 (MSVC++). Microsoft attempted to minimize the deviations between standard C++ and Managed Extensions for C++, resulting in core differences between the two being syntactically obscured. MSVC++ 2003 and 2005 also provided support for writing programs in Managed C++. In 2004, Managed Extensions for C++ was deprecated in favor of [[C++/CLI]], a second attempt by Microsoft at supporting programming for the [[Common Language Infrastructure]] using C++.<ref name="Sutter2006">{{cite web|url=http://www.gotw.ca/publications/C++CLIRationale.pdf|last=Sutter|first=Herb|title=A Design Rationale for C/C++|page=6|url-status=live|access-date=2018-06-12|archive-date=2017-08-30|archive-url=https://web.archive.org/web/20170830063554/http://www.gotw.ca/publications/C++CLIRationale.pdf}}</ref>
 
== Design ==
Managed C++ is not a complete standalone, or fully fledged programming language, but it is merely a set of grammatical and syntaxual extensions implemented by [[Microsoft]] to bring C++ to the .NET Framework (essentially, the CLR) and to allow for managed programming for C++ programmers.
''Managed'' refers to [[managed code]] that it is run in, or ''managed'' by, the .NET [[virtual machine]] that functions as a [[sandbox (security)|sandbox]] for enhanced security in the form of more runtime checks, such as buffer overrun checks. Additionally, applications written in Managed C++ compile to [[Common Intermediate Language|CIL]]—Common Intermediate Language—and not directly to native [[central processing unit|CPU]] instructions like standard C++ applications do.
 
Managed C++ code could inter-operate with any other language also targeted for the [[Common Language Runtime|CLR]] such as [[C Sharp (programming language)|C#]] and [[Visual Basic .NET]] as well as make use of features provided by the [[Common Language Runtime|CLR]] such as [[garbage collection (computer science)|garbage collection]]. This means Managed C++ occupies a unique position in the gallery of .NET languages. It is the only language that can communicate directly with .NET languages (such as C#, VB.NET) as well as native C++. The other .NET languages can only communicate with C++ code via [[Platform Invocation Services|PInvoke]] or [[Component Object Model|COM]]. But since Managed C++ can communicate directly in both managed and standard C++ contexts, it is often used as a "bridge".
== Scope of this article ==
 
== Functionality ==
It is also advised to the reader that this article be interpreted merely as informational and not to provide a tutorial on Managed Extensions for C++. While conventions and syntax may be explained here, it will not provide a 'crash-course' or anything like that on how to program using Managed C++. Also, as stated before, this article will eventually be superceded by the new standard, [[C_Plus_Plus/CLI|C++/CLI]].
Programs coded in Managed C++ provide additional functionality of the .NET Framework and the [[Common Language Runtime|CLR]]. Most notable of these is [[garbage collection (computer science)|garbage collection]], which relieves the programmer of manual memory management. The garbage collector (GC) is handled by the CLR. Memory management is executed quite quickly, but for more performance critical applications, native, unmanaged code is most likely the preferred option.
 
Managed C++ is geared towards object-oriented programming. A major difference between standard C++ and Managed C++ is that [[multiple inheritance]] is not supported, and a class managed under the CLR's garbage collector cannot inherit more than one class. This is because of a limitation of the CLR.
== Who would use Managed C++ ==
 
Key features:
One of the many things about Managed C++ is the question of its useability. Who would use Managed C++ when C# and Visual Basic .NET are already very powerful languages to use for programming with the .NET Framework?
* Extensible metadata: information provided to describe the structure and types of a managed component. It can be extended and reused to create software components. It is used heavily in C# and Visual Basic .NET
* Garbage collection: the CLR is fully managed by a garbage collector for memory management automated by the CLR itself, i.e. the delete operator need not be called in managed C++ code.
* Interoperability with .NET languages: code targeted for the .NET Framework produces [[Common Intermediate Language|Microsoft Intermediate Language]] (MSIL, similar to Java bytecode) output and thus, modules compiled and components (assemblies rather) can be reused by other program components written in another language targeting the .NET Framework, such as JScript .NET, C#, Visual Basic .NET and other 3rd party languages for .NET.
* Versioning: new methods and data members can be introduced into existing managed classes without breaking binary compatibility with existing client side software.
* Binary headers: allows reusing of precompiled metadata; any .exe, .dll, .obj or .netmodule compiled into MSIL can be referenced from a C++ source file.
* Buffer overflow protection - with the introduction of garbage collection into C++, Managed C++ is less prone to the common [[buffer overflow]] errors caused by the absence of data type checking in standard C++. The garbage collector helps to reduce (not completely though) the frequency of these errors.
* .NET framework [[Base Class Library]] - Managed C++ also has the potential to be less verbose than standard unmanaged code, since all managed function calls and inherited classes are derived from the .NET Framework Base Class Library (BCL, sometimes referred to as FCL or Framework Class Library), whose API provides TCP/IP networking capabilities, textual manipulation functions, data access (from ODBC to SQL), XML services (from XSD to XSL), GUI programming (Windows Forms), mail services (SMTP), cryptography (X509 Certificates and XML digital signatures), MSIL generation (essentially emitting instructions in MSIL), file I/O, manual manipulation of the CLR garbage collector and management information to manipulate the WMI console.
 
=== Advantages over native code ===
The main purpose of Managed C++ was not only to provide C++ programmers to utilize their skills in C++ to access a rich and stable platform for Windows Programming, but also to allow existing C++ projects and source code to be speedily ported over to the .NET Framework, should programmers require it.
* Managed and unmanaged code can be mixed together in the same [[Assembly (CLI)|CLI assembly]] seamlessly. This allows the programmer to keep unmanaged code that cannot be ported over to the [[.NET Framework]] without re-writing it completely. Some ramifications of using this hybrid convention are present though.
* Managed C++ is the only language that can contain unmanaged code and natively communicate with all other .NET languages. Managed C++ is thus very convenient for interoperability between programmers who use different languages, including those in the .NET theater and those who use standard C++.
 
=== Disadvantages compared to unmanaged code ===
Since Microsoft has already released plans to base its next generation operating system, [[Longhorn]], partly on managed code, it would be logical to assume that existing technologies that Microsoft implements itself would be ported and re-implemented to provide the same base design and accessibility as the technology changes. It can be assumed that Managed C++ was conceived soley based on that reason.
* Managed C++ introduces a lot of new keywords and syntactic conventions that can impair the readability of code, especially if C++ code is included directly and interacts directly with Managed C++ code in the same assembly.
* Managed C++ is superseded by [[C++/CLI]] and thus obsolete as [[C++/CLI]] has been standardized.
 
=== Disadvantages compared to fully managed code ===
== Additional or ammended functionality provided in Managed C++ ==
* Managed C++ requires a slightly longer development time than other .NET languages that could be applied to projects that still produce the same results. The use of pointers may or may not be a requirement, because managed C++ has both value types (__value struct and __value class) and reference types (__gc struct and __gc class).
* Managed C++ fully support [[ASP.NET]] web applications, even though the development is more difficult than with other .NET languages, including some other third party languages.
* Managed C++ includes only support for templates (for interoperability with native C++) but no support for generics (for interoperability with all the other .NET languages). [[C++/CLI]] supports both templates (at compile time) and generics (at run time).
 
== Examples ==
Programs coded in Managed C++ provide additional functionaliy of the .NET Framework and the CLR. Most notable of these is garbage collection, which relieves the programmer of manual memory management. The garbage collector (or GC) is handled by the CLR. Memory management is executed quite quickly, but for more performance critical applications, native, unmanaged code is most likely the preferred option.
The following examples depict the use of Managed C++ as compared to standard C++:
 
* (Global change) Existing C++ to be ported over the CLR must be appended with the following:
Also, C++ has evolved much over time and most implementations of the langauge are object oriented. Managed C++ and the use of classes and class based objects remains prevelant like in Visual C++. The only major change to this in Managed C++ is that the capabilities of multiple inheritance are not supported. This is because of a limitation of the CLR and the functions of the garbage collector. A class managed under the garbage collector cannot inherit more than one class, further is explained in the proceeding sections.
<syntaxhighlight lang="cpp">
<!-- must revise: neutrality disputed:
'''Exensible Metadata'''
 
''- Which is the information provided to describe the structure and types of a managed component. It can be extended and reused to create software components. It is used heavily in C# and Visual Basic .NET''
 
'''Garbage Collection'''
 
''- The CLR is fully managed by a garbage collector, so all applications and programs coded in Managed C++ need not worry about memory management. It is a process automated by the CLR itslefl i.e. the delete operator need never be called in managed C++ code. ''
 
'''Code Reusability and Interoperability'''
 
''- Code targeted for the .NET Framework produces MSIL (MS Intermediate Language, similar to Java bytecode) and thus, modules compiled and components (assemblies rather) can be reused by other program components written in another language targeting the .NET Framework, such as JScript .NET, C#, Visual Basic .NET and other 3rd party languages for .NET. This provides the potential to use Managed C++ code in your simple JScript .NET scripts or applications. <!-- its not like u would anyway -->
<!--
'''Versioning Capabilities'''
 
''- New methods and data members can be introduced into existing managed classes without breaking binary compatibility with existing client side software.''
 
'''Binary Headers'''
 
''- This provides for the reusing of any precompiled metadata; any .exe, .dll, .obj or .netmodule compiled into MSIL can be referenced from a C++ source file and be reused. This is comparably faster than referencing an uncompiled C++ source code file.''
 
'''Increased Code Protection'''
 
''- With the introduction of garbage collection into C++, Managed C++ is less prone to the common [[buffer overflow]] errors caused by the absence of data type checking in unmanaged C++. The garbage collector helps to reduce (not completely though) the frequency of these errors.''
 
'''Unified Programming'''
 
''- Managed C++ also has the potential to be less verbose than standard unmanaged code, since all managed function calls and inherited classes are derived from the .NET Framework Base Class Library (BCL, sometimes referred to as FCL or Framework Class Library), whose API provides TCP/IP networking capabilities, textual manipulation functions, data access (from ODBC to SQL), XML services (from XSD to XSL), GUI programming (Windows Forms), mail services (SMTP), cryptography (X509 Certificates and XML digital signatures), MSIL generation (essentially emitting instructions in MSIL), file I/O, manual manipulation of the CLR garbage collector and even providing management information to manipulate the WMI console.''-->
 
=== Advantages of using Managed C++ over unmanaged code ===
 
* Programmers need not worry about manual memory management, any classes under Managed C++ can be designated to be managed by the CLR garbage collector simply by adding a modifier keyword, __gc before the class keyword. i.e. __gc class new { }; is managed under the garbage collector.
 
* Managed and unmanaged code can be mixed together in the same assembly seamlessly. This provides for the programmer to keep unmanaged code that cannot be ported over to the .NET Framework in the same program without re-writing it completely. Some ramifications of using this hybrid convention are present though.
 
* Managed C++ is the only language able to natively communicate with all other .NET langauges ''and native umanaged C++ code''. Managed C++ is thus very convenient for interoperability between programmers who use different langauges, including those in the .NET threatre and those who use unmanaged C++.
 
=== Disadvantages of using Managed C++ over unmanaged code ===
 
* Managed C++ introduces alot of new keywords and syntaxual conventions that can impede on the readability of managed code, especially if C++ code is included directly and interacts directly with Managed C++ code in the same assembly.
 
* Like in [[Java programming language|Java]], there is the presence of an unnecessary overhead of features that most Managed C++ programmers and programs don't really need. This will reduce performance on most applications. The overhead of a garbage collector is the main performance inhibitor. In almost all performance critical applications, unmanaged native code is the preferred option.
 
* Managed C++ is to be superceded by [[C_Plus_Plus/CLI|C++/CLI]] and thus is to be made obsolete when C++/CLI is released as a final standard.
 
* Managed C++ does not support ASP.NET web applications, which is a capability supported by all languages targeting the .NET Framework, including other third party langauges.
 
* Managed C++ requires a slightly longer development time than other [[dotnetFramework|.NET]] languages that could be applied to projects that still produce the same result, since the implications of pointers in C++ are still required, even in managed C++ code.
 
* Managed C++ is a language only readily available to programmers already familar with [[C Plus Plus|C++]] or another derived language. Visual Basic programmers for example, will have trouble implementing Managed C++ in their solutions, while C# programmers however, may have some difficulty, but can adopt to Managed C++ quicker.
 
* Managed C++ includes no support for generic programming. [[C_Plus_Plus/CLI|C++/CLI]] is to support this though.
 
== Main Programmatic Changes in Managed C++ ==
'''The following list of changes pertain to the theatre of differences in Object Oriented Programming compared to programming with unmanaged C++.'''
 
 
* Existing C++ to be ported over the CLR must be appended with the following:
<pre>
//hello.cpp
 
Line 92 ⟶ 52:
using namespace System;
 
int main()
{
Console::WriteLine(L"Hello, world!");
return 0;
}
</syntaxhighlight>
</pre>
 
A new preprocessor directive
 
<syntaxhighlight lang="cpp">#using <mscorlib.dll></syntaxhighlight>
 
is required. In addition to that, more #using directives are required to import more libraries to use more namespaces in the Base Class Library, such as
 
<syntaxhighlight lang="cpp">#using <System.Windows.Forms.dll></syntaxhighlight>
 
and
 
<syntaxhighlight lang="cpp">using namespace System::Windows::Forms;</syntaxhighlight>
 
to utilizeuse Windows Forms.
 
* To compile code to target the CLR, a new compiler option must be introduced.
Line 116 ⟶ 77:
cl.exe hello.cpp /clr
 
/clr enables any code referencing the .NET Framework to be compiled as MSIL[[Common Intermediate Language|CIL]].
 
* A class can be designated to be garbage collected via the <code>__gc</code> extension keyword.
 
<syntaxhighlight lang="cpp">
<pre>
//gc.cpp
 
#using <mscorlib.dll>
 
__gc class gc
{
int* i;
char* g;
Line 131 ⟶ 93:
};
 
int main()
{
while (true)
{
gc*^ _gc = newgcnew gc();
}
return 0;
}
</syntaxhighlight>
</pre>
 
The preceding code can be compiled and executed without any fear of [[memory leaksleak]]s. Because class <code>gc</code> is managed under the garbage collector, there is no need to call the <code>delete</code> operator. Thus this program can run for an indefinite period of time without wasting any memory. To achieve the same with unmanaged code, the <code>delete</code> keyword is required:
 
<syntaxhighlight lang="cpp">
<pre>
//nogc.cpp
 
class gc
{
int* i;
char* g;
Line 150 ⟶ 115:
};
 
int main()
{
while (true)
{
gc* _gc = new gc();
delete _gc;
Line 157 ⟶ 124:
return 0;
}
</syntaxhighlight>
</pre>
 
Notes:
NOTES:
* A __gc designated class can have a constructor declared.
* A __gc designated class can have a destructor declared.
* A __gc designated class cannot inherit more than one class. (This is a limitation of the CLR)
* A __gc designated class cannot inherit another class that is not __gc designated.
* A __gc designated class cannot be inherited by another class that is not __gc designated.
* A __gc designated class can implement any number of __gc interfaces.
* A __gc designated class cannot implement an unmanaged interface.
* A __gc designated class is by default not made visible outside of its own assembly. Use
<syntaxhighlight lang="cpp">public __gc class hey { };</syntaxhighlight>
 
the public keyword to modify the access of the a __gc designated class.
A __gc designated class can have a constructor declared.
 
A __gc designated class can havebe destroyed manually using the delete keyword, but only if the __gc designated class has a destructoruser-defined declareddestructor.
 
* An interface can be declared with the __gc extension keyword preceding it. Such as:
A __gc designated class cannot inherit more than one class. (This is a limitation of the CLR)
 
<syntaxhighlight lang="cpp">
A __gc designated class cannot inherit another class that is not __gc designated.
//interface.cpp
#using <mscorlib.dll>
 
__gc __interface ClassBase
A __gc designated class cannot be inherited by another class that is not __gc designated.
{
void Init();
int Common();
}
</syntaxhighlight>
 
The preceding code must be compiled with /clr and /LD to produce a simple DLL file.
A __gc designated class can implement any number of __gc interfaces.
 
Notes:
A __gc designated class cannot implement an unmanaged interface.
* A __gc __interface cannot contain any data members, static members, nested class declarations and no access specifiers.
* A __gc __interface can only inherit from another __gc __interface interface or the System::Object. Inheritance from System::Object is the default behavior.
* A __gc __interface cannot contain any implementation (body code) of its declared function prototypes.
 
== Comparison with other languages ==
A __gc designated class is by default not made visible outside of its own assembly. Use
public __gc hey class { };
 
The following contains main points and programmatic standards that differ between Managed C++ and other well known programming languages that are similar in concept.
the public keyword to modify the access of the a __gc designated class.
 
=== Standard C++ ===
'''Disadvantages'''
* [[Native mode|native]] C++ code may be faster at runtime.
* C++ does not require an installation of an associated compiler and managed runtime environment on the target system
* C++ supports [[generic programming]]. Until the final release of C++/CLI however, Managed C++ programmers must revert for workarounds for using generics.
* C++ supports the keyword "const" and [[const correctness]]. Managed C++, like Java and C#, does not contain this feature. An alternative is to make a managed class [[Immutable object|immutable]], or restricting set accessors on public interfaces.
* C++ code is not constricted by the CLR's restrictions. For example, the CLR does not allow classes to inherit other classes privately nor protected, thus the following will produce a compiler error:
<syntaxhighlight lang="cpp">
public __gc class one { int i; };
public __gc class two: private one { int h; i = h; }; // error
public __gc class three: protected one { int h; i=h;}; // error
</syntaxhighlight>
* Managed C++ __gc classes cannot inherit from more than one class, as such the following will produce a compiler error:
<syntaxhighlight lang="cpp">
__gc class a {};
__gc class b {};
__gc class c: public a, public b {}; //will produce an error
</syntaxhighlight>
 
'''Advantages'''
A __gc designated class can be destroyed manually using the delete keyword, but only if the __gc designated class has a user-defined destructor.
* Managed C++ supports a greater degree of [[Reflection (computer science)|reflection]] than regular C++, which is generally much more convenient depending on the function of the code, or what the code is intended for.
* Managed C++ can inter-operate with all other .NET capable languages, including other third party languages.
* Managed C++ is garbage collected. In standard C++, memory management and allocation is the responsibility of the programmer.
 
=== Java ===
* An interface can be declared with the __gc extension keyword preceding it. Such as:
'''Differences'''
* Running Java code requires an appropriate virtual machine, while running Managed C++ code requires an appropriate implementation of the .NET Framework.
 
'''Disadvantages'''
<pre>
* Java provides a documentation on the source code, while Managed C++ does not.
//interface.cpp
* Java has many other development tools available for Java programmers to use, while Managed C++ is only available under [[Visual Studio .NET]].
#using <mscorlib.dll>
 
'''Advantages'''
__gc __interface ClassBase {
* Managed C++ can access the computer system on a low level interface much more easily than Java. Java programmers must use the [[Java Native Interface|JNI (Java Native Interface)]] to use low level services of the host operating system.
void Init();
int Common();
}
</pre>
 
The preceding code must be compiled with /clr and /LD to produce a simple DLL file.
 
=== C# ===
NOTES:
'''Differences'''
* While C# supports pointers just as in C++, this feature is turned off by default.
 
'''Disadvantages'''
A __gc __interface cannot contain any data members, static members, nested class declarations and no access specifiers.
* Like [[Java (programming language)|Java]], C# is syntactically simpler when dealing with managed code.
* C# can achieve basically the same result as Managed C++, as all syntactic and structural conventions remain strikingly similar.
* Managed C++, though it is a strongly typed language due to its introduction into the CLR, can be prone to errors if unmanaged compiled code is introduced in the same codebase, while C# is pure MSIL.
 
'''Advantages'''
A __gc __interface can only inherit from another __gc __interface interface or the System::Object. Inheritance from System::Object is the default behaivour.
* C# must use the .NET Framework and provided class libraries to access the computer system on a low level.
* Porting over applications to the .NET Framework from C or C++ is much easier to do using Managed C++.
* The Microsoft Visual C++ .NET compiler, which compiles Managed C++ to target the .NET Framework, produces a much more matured set of instructions in its resultant assembly, thus improving performance.
 
== See also ==
A __gc __interface cannot contain any implementation (body code) of its declared function prototypes.
* [[C++/CLI]]
 
== References and External Links ==
{{Reflist|2}}
[http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vcmxspec/html/vcmanagedextensionsspec_start.asp Managed Extensions for C++ (at MSDN)]
 
== External links ==
[[Managed C Plus Plus]]
* [https://msdn2.microsoft.com/en-us/library/Aa712867 Managed Extensions for C++ (at MSDN)]
* [https://boxedapp.com/blog/2008/07/16/c-cli-how-to-use-managed-c-dll-when-microsoft-visual-c-redistributable-is-not-installed/ Article: C++ / CLI – How To Use Managed C++ DLL when Microsoft Visual C++ Redistributable is not installed?]
 
{{Common Language Infrastructure}}
----
 
[[Category:C++ programming language family]]
TO BE FINISHED
[[Category:.NET programming languages]]
[[Category:Microsoft Visual Studio]]