Visual c ++. NET Programming: hosting C ++ Overview

Source: Internet
Author: User
Tags mscorlib
   1. What is hosting C ++?

To answer this question, you must first understand what is managed ). Hosting is. net is a new programming concept integrated with the general language runtime (CLR). Therefore, we can regard "hosting" as ".. net ". So what is "general language runtime "? The general language runtime is the execution lead of. NET Framework applications. It provides many services, including code management (load and execution), type security verification, metadata (advanced type information) Access, memory management for management objects, and code management, interaction and operability of COM objects and pre-generated DLLs (non-managed code and data), and support for developers' services.

That is to say, the use of managed C ++ means that our code can be managed by Clr and can develop new features such as automatic garbage collection and inter-program access.. NET Framework application.

The C ++ application triggered by the concept of hosting consists of three parts: hosting code, hosting data, and hosting.

(1)Managed code: The. NET environment provides many core runtime services, such as exception handling and security policies. To be able to use these services, you must provide some information code (metadata) to the runtime environment, which is the managed code. All C # and VB. net, JScript. net is hosted by default, but visual c ++ is not hosted by default. You must use the command line option (/CLR) in the compiler to generate managed code.

(2)Managed Data: Managed data is closely related to managed code. Managed Data is the data allocated and released by the garbage collector running in the public language. By default, C #, Visual Basic, and JScript. NET data are hosted data. However, by using special keywords, C # data can be labeled as unmanaged data. Visual c ++ data is not hosted by default, even when the/CLR switch is used.

(3)Hosting: Although visual c ++ data is not hosted by default, you can use the "_ GC" keyword to mark the class as a Managed class. As shown in the name, it indicates that the memory of the class instance is managed by the garbage collector. In addition, a Managed class can also be. net Framework members, which can bring about the benefit that it can correctly perform operations with classes written in other languages, for example, hosted C ++ classes can be inherited from visual basic classes. But there are also some restrictions, such as hosting classes can only inherit from one base class. It should be noted that in a hosted C ++ application, both managed classes and unmanaged classes can be used. The unmanaged class here is not a standard C ++ class, but a class hosting the _ nogc keyword in the C ++ language.

  2. Project types that can be used to develop. Net frameworks with managed C ++

The use of managed C ++ should be written by C ++ programmers. net Framework application is the best choice, by integrating in Visual Studio.. Net Development Environment hosting C ++ wizard, we can create the following types of development.. NET Framework project type:

(1) Hosting C ++ applications: used to create a separate C ++ application that supports hosting extensions. You can also use it to create any types of applications, including.. NET Framework client applications.

(2) Hosting C ++ Class Library: used to create a C ++ DLL that supports hosting extensions. It can be used to generate a hosted component that can be called by. NET Framework applications.

(3) Hosting C ++ empty projects: used to create an empty Managed Project. This project only contains the correct compilation and link options that support hosting extensions. You can use it to add an existing C ++ source file to a managed environment.

(4) Hosting C ++ Web Services: this service is used to create two projects: C ++ hosting extension projects and deployment projects.

  3. Main differences between hosting C ++ and Standard C ++

Although managed C ++ is built from standard C ++, it is essentially different from standard C ++, which is mainly reflected in the following aspects:

  (1) The namespace is widely used)

Namespace is a type of logical naming scheme ,. net uses this naming scheme to group types by logical category of related functions. namespace can make it easier for developers to browse and reference types in code. Of course, we can also regard the namespace as a "Class Library name ".

Although Microsoft has long supported namespace programming in Visual C ++, it has rarely attracted widespread attention of Visual C ++ programmers. Now in hosting C ++ programs, we must use this method, that is, using the # using and using keywords. For example, the following simple program code outputs "Hello World" on the console ":

# Using
Using namespace system;
Int main (void)
Console: writeline (S "Hello World ");
Return 0;

In the code, # using is used to input a metadata file to a hosted C ++ program. These files can be msil containing hosted data and structure (Microsoft intermediate language, Microsoft intermediate language) files, such as DLL, EXE, and OBJ files. Mscorlib. dll is a core class library of the. NET Framework, including the main namespace system. The second line of code "using namespace system;" of the program is used to use the system namespace. System is the root namespace Of the. NET Framework and contains the most basic types, such as system: Io used for input/output of data streams.

With the continuous development of hosted C ++ programs, we will soon find that many types of references must be carried out before the program using # using and using.

  (2) changes in basic data types

We know that the data types in the Standard C ++ language are very rich. The data types hosted by C ++ are more abundant, including not only the data types in the Standard C ++, but also the _ int64 (64-bit integer) decimal (96-digit decimal number), string * (string type), and object * (Object Type). Their data types are listed in Table 1-1.

Type description Standard C ++ type name Managed C ++ type name Length (BIT)
Boolean Bool Bool 8
Character Type Char Signed Char 8
Unsigned character type Unsigned char Char 8
Short integer Short [int] Short 16
Unsigned short integer Unsigned short [int] Unsigned short 16
Integer Int Int or long 32
Unsigned integer Unsigned [int] Unsigned Int or long 32
Long Integer Long [int] Long 32
Unsigned long integer Unsigned long [int] Unsigned long 32
Single precision floating point type Float Float 32
Dual-precision floating point Double Double 64
Long dual-precision floating point type Long double -- 64
Unicode characters -- Wchar_t 16
64-bit integer -- _ Int64 64
Unsigned 64-bit integer -- Unsigned _ int64 64
96-digit decimal Value -- Decimal 96
Object Type -- Object * 32
String type -- String * --

Note that when defining a variable for a string or object, note that a star number ("*") is required, but this variable is not a pointer variable, this is different from the meaning of Standard C ++. For example, the above Code can be changed:

# Using
Using namespace system;
Int main (void)
String * Hello = s "Hello World ";
Console: writeline (Hello );
Return 0;

 (3) three managed C ++ types are added: __gc class, _ value class, and _ GC interface.

A _ GC class or structure means that the lifecycle of the class or structure is automatically managed by the. NET development platform and garbage collection. You do not have to call Delete to delete the class or structure. Defining a _ GC class or structure is basically similar to the Standard C ++. The difference is that _ GC is added before the class or struct, for example, the following code:

_ GC class G {
Int K;
Int sum (INT );

G: sum (int I) {return I * (I + 1)/2 ;}
Int main ()
G * g = new G;
Console: writeline (G-> sum (4); // output 10
Return 0;


A. A _ GC class cannot inherit from an unmanaged class and cannot contain an unmanaged class derived from it. However, a _ GC class can be inherited from a Managed class at most.

B. A _ GC class cannot be defined as a friend class or contain a friend member function. The so-called friend functions are used to enable the private and protection type members in the external functions category.

C. A _ GC class cannot be declared or defined, and the new or delete operations can be reloaded, and the class cannot contain using and other declarations.

The _ value class is used to use small data items with short lifecycles. It is different from the _ GC class. _ GC class data is distributed in the CLR heap, while _ value class objects are in the running stack or called NDP (. net developer platform ,.. Net developer platform) created in the heap to avoid the overhead caused by the constant allocation and release of space by the garbage collector. A _ value class can be declared as a local variable, parameter, and return value, it can also be embedded into a _ GC class, as a static variable, or as a variable allocated in the C ++ heap. For example, the following code:

# Using
Using namespace system;
_ Value struct v {int I ;};
_ GC struct G {v ;}; // embed it into the _ GC class
V f (V v) {// defines a global function whose values are stored in the running stack.
V. I + = 1; // the value of the original parameter V is not affected.
Return V; // return the value of the V structure type.
Int main (void)
V V1 = {10}; // declare and initialize in the running Stack
V v2 = f (V1); // call the F function. In this case, I in V1 is 10, while I in V2 is 11.
G * Pg = new G; // allocate heap space for G instances
Pg-> V = V1; // I in PG V is 10
Pg-> v. I + = v2. I; // in pg v, I is 10 + 11 = 21
Console: writeline (v1. I); // The output result is 10.
Console: writeline (v2. I); // The output result is 11.
Console: writeline (PG-> v. I); // The output result is 21.
Return 0;

In addition, all the _ GC objects are derived from the class system: object, so it is easy to use the set and ing functions in the _ GC class. However, the _ value type is not shared with this base class. Therefore, the _ value type cannot be directly used as the object * real parameter in the function. To solve this problem,. Net allows us to use the _ box keyword to treat a _ value type as a _ GC object. In this case, the _ value type is encapsulated into a _ GC pile (stub) and copied to the NDP heap. Because box does not have the implicit conversion function in hosting C ++, the conversion type must be specified during conversion.

Hosting the _ GC interface in C ++ best reflects the idea of the COM interface. Its definition and declaration are very simple. Besides the different keywords, similar to the declaration of A _ GC class. For example, the following code defines an interface imybase, which contains an F method:

_ GC _ interface IBASE {
Void F ();

It should be noted that all methods in the interface are purely virtual and public by default. We do not need to use the virtual keyword before the method or add "= 0" after the method ". Second, a _ GC interface cannot contain data members or static members, nor can it contain declarations of any classes. The following example shows how to use the _ GC interface:

# Using
Using namespace system;

_ GC _ interface ibase1 {
Int F (INT );
_ GC _ interface ibase2 {
Int F (INT );
_ GC struct C: ibase1, ibase2 {
Int F (int I) {// Implementation of the Interface Method
Return 2 * I-1;

Int main (void ){
C * c = new C;
Console: writeline (c-> F (1). tostring (); // The output result is 1.
Console: writeline (_ try_cast (C)-> F (2). tostring ());
// The output result is 3.

Console: writeline (_ try_cast (C)-> F (3). tostring ());
// The output result is 5.

Return 0;

In the code, __try_cast is used to convert an object into a specified type and automatically handle the exception when the type conversion fails. Tostring is used to describe an object as a string.

 (4) Simplified attribute operations

The. NET attribute can be used in the _ GC class. This attribute simplifies the calling operation of the attribute function, which is different from the attribute in the Standard C ++. In standard C ++, the GET _ and put _ member functions are used to set or obtain the values of relevant properties. Now, hosting attribute operations in C ++ is like operating an attribute variable, for example, the following code:

# Using
Using namespace system;

_ GC class G {
_ Property int get_size (){
Console: writeline (S "GET _ attribute ");
Return nsize;
_ Property void set_size (int I ){
Console: writeline (S "SET _ attribute ");
Nsize = I;
Int nsize;

Int main (){
G * Pg = new G;
Pg-> size = 10; // call set_size
Int I = PG-> size; // call get_size
Console: writeline (I );

Program result:

Set _ attributes

Get _ attributes


It should be noted that the hosted C ++ uses the _ property keyword to define a member function of an attribute. From the code, we can see that set _ and get _ are used in the member function names for setting and obtaining properties respectively, so that the compiler will automatically generate a pseudo member variable size, the variable name is the name after the SET _ and get _ member functions. Do not use this pseudo-member variable size in the GET _ member function code any more. This will cause recursive calls to the function.

  (5) delegate the hosting of C ++

In C/C ++, the address of a function is the memory address. This address does not contain any additional information, such as the number of parameters of the function, the parameter type, the return value type of the function, and the call specification of the function. In short, C/C ++ callback functions do not have type security. The. NET Framework adds a type-safe mechanism on the basis of callback functions, called delegation.

The delegate Method for hosting C ++ is not as complex as C #. It simplifies the internal mechanism of most delegates and makes it easy to use. For example, the following code:

# Using
Using namespace system;

_ Delegate int getdayofweek (); // delegate method declaration
_ GC class mycalendar
Mycalendar (): m_ndayofweek (4 ){}
Int mygetdayofweek (){
Console: writeline ("non-static method ");
Return m_ndayofweek;
Static int mystaticgetdayofweek (){
Console: writeline ("static method ");
Return 6;
Int m_ndayofweek;

Int main (void)
Getdayofweek * pgetdayofweek; // declare the delegate Type Variable
Int ndayofweek;

// Bind the static method mystaticgetdayofweek of the class to the Delegate
Pgetdayofweek = new getdayofweek (0, & mycalendar: mystaticgetdayofweek );
Ndayofweek = pgetdayofweek-> invoke (); // delegate call
Console: writeline (ndayofweek );

// Bind a class instance to a delegate
Mycalendar * pcal = new mycalendar ();
Pgetdayofweek =
Static_cast (Delegate: Combine (pgetdayofweek,
New getdayofweek (pcal, & mycalendar: mygetdayofweek )));
Ndayofweek = pgetdayofweek-> invoke ();
Console: writeline (ndayofweek );

// Delete the bound delegate class instance
Pgetdayofweek =
Static_cast (Delegate: Remove (pgetdayofweek,
New getdayofweek (pcal, & mycalendar: mygetdayofweek )));

Return 0;

The output result is:

Static Method

Static Method

Non-Static Method


  4. Conclusion

In short, using managed C ++ is written by C ++ programmers. net Framework is the best choice for applications.. NET Framework, avoiding the use of other languages such as C # and VB. net.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.