Creation and reference of managed objects
In the previous article we have demonstrated the creation of a managed object for the following C # code:
System. Object x = new System. Object();
Its equivalent code in C + +/CLI is as follows:
System::Object^ x = gcnew System::object();
and the traditional The syntax comparison created by C + +,
p* x = new P();
It is easy to see that for managed objects, the following two syntaxes are introduced:
- Implement managed object creation with gcnew instead of new
- Use ^ instead of * to implement a pointer to a managed object
Objects created in this way can be directly supported by the CLR and can be used in C #. Managed object pointers are used in a similar way to traditional object pointers, and can be used directly:
System::Object^ x = gcnew System::object();
auto str = x->tostring ();
In addition, C + +/CLI also has a syntax similar to the reference to a managed object in a
System::Object^ x = gcnew System::object();
System::Object% y = *x;
auto str = y.tostring ();
Because this approach does not have a corresponding syntax in C #, it feels strange to use and is not convenient for other. NET language integrations.
Definition of managed type
We can also customize managed types, in the CLR, where managed types are classified as reference types (class) and value types (structs), and are defined separately in C + +/CLI as follows:
Reference type:
publicrefclassMyClass
{
};
Value type:
publicvalueclassMyClass
{
};
It is relatively easy to use a ref or value tag as a managed type in the class definition in ISO C + +.
Enumeration
The enumeration is defined in the same way as the Enum class of c++11, which can be applied to both managed and unmanaged types as numbers.
Publicenumclasssomecolors { Red, Yellow, Blue };
Or a more precise representation:
Publicenumclass somecolors: char {Red, Yellow, Blue};
Array
Add array <T> ^ in C + +/CLI to define arrays.
array<int> ^a = gcnewarray<int> (+) {1, 2, 3};
Or use the full version of it:
CLI::array<int> ^a = gcnew CLI::array<int> {1, 2, 3};
Indeterminate parameters
For the syntax of indeterminate arguments in C #:
void foo (paramsstring[] args)
The corresponding version in C + +/CLI is:
void foo (...) array<String^>^ args)
Building bridges between C + + and C + + with CLI (ii)-Basic syntax