Research on Visual C # packing and unpacking

Source: Internet
Author: User
Tags mscorlib

Before discussing this question, let's first ask these questions to systematically understand the theme we are going to explore today.

Viewers may have used a wide variety of classes such as the System. Console class or. NET class library countless times. So what I want to ask is where they actually come from? C # How do I contact them? Is there a mechanism or type system that supports personalized scaling? What types of systems are available for us? If we PL don't even know these problems, let alone Why, C # will probably shut us out.

So let's stop our work and take a good look at the general Type System, which is one of the important technologies and foundations of. NET. As the name suggests, CTS is a general type system that exists to realize the rules that must be followed when applications declare and use these types. Although you may not be familiar with this, I still want to emphasize that. Net divides the type of the entire system into two categories-value type and reference type. At this point, you may be angry: After talking about this for a long time, you seem to have not yet begun to answer the question! Don't panic! Knowing the Characteristics of A. Net type system does not mean that you really understand the principles and significance of this type system.

Most object-oriented languages have two types: original types (inherent types of languages, such as integers and enumerations) and classes. Although the object-oriented technology is very powerful in terms of modularization and alization, there are also some problems, such as the system type problem mentioned now, history tells us that the two groups of types cause many problems. The first is the compatibility problem. This is also Microsoft's hard-hitting point. Most OO languages have this weakness because their original types do not have a common basis, so they are not really objects in nature, and they are not derived from a general base class. No wonder, Anders Heijlsberg laughed and called it "Magic type ".

Because of this defect, when we want to specify a Method that can accept any type of parameter supported by the language, the same problem affects our brain again-incompatible. Of course, for C ++'s PL danale, it may be no big deal. They will proudly say, you just need to use the overloaded constructor to write a Wrapper Class for each original type! Well, it can coexist. But how can we get the result that we are most concerned about from this magic? As a result, they are still confident to open Boarland and skillfully write a function that has been overloaded to get results from the Wrapper Class just now. Brothers and sisters, under the historical conditions at that time, your actions were pioneering, but compared with the present, you will pay the price-inefficiency. After all, C ++ is more dependent on objects than object-oriented. Recognizing the reality is always more rational than looking at the dead! After making so much effort, I finally finished the preparations. What I want to say is: The CTS in the. Net environment has brought us convenience. First, everything in CTS is an Object; second, all objects are from a base class-System. Object type. For more information about System. Object, see Microsoft technical documentation. Here we will briefly talk about the two types mentioned above: Value Type and Reference Type.

One of the biggest features of the CTS value type is that they cannot be null. The implication is that the variable of the Value Type always has a value. In C #, it includes the original type, structure, and enumerator. Note: When passing a value type variable, we actually pass the value of the variable instead of the reference of the underlying object, this is quite different from the situation where variables of the reference type are passed. The CTS reference type is like a type-safe pointer, which can be null. It includes classes, interfaces, delegation, arrays, and other types. Compared with the features of the pre-nominal value type, when we allocate a reference type, the system will allocate a value (memory allocation and location) on the background stack and return a reference to this value; if the value is null, no reference or type points to an object. This means that when we declare a variable of the reference type, we are operating on the reference (address) of this variable rather than the data.

When talking about this place, the main character of this article finally debuted-comrades who want to vomit blood or vomit, please be patient again. I would like to ask a question first: how can we effectively expand and improve the system performance when using this multi-type system? Maybe it's the discussion on the blackboard. The Seattle team put forward the Box and UnBox ideas. To put it simply. Packing is the process of converting value type to reference type. (In fact, this idea was born eight years ago ). Next we will further discuss the process of packing and unpacking in detail. During the discussion, the answers to the questions we just mentioned are easily solved.



First, let's take a look at the packing process, so we need to do two jobs first: 1. Write the routine; 2. Open ILDASM (MSIL code viewing tool). For this, let's take a look at the following code:

Using System;

Namespace StructApp
{
///
/// Summary of BoxAndUnBox.
///
Public class BoxAndUnBox
{
Public BoxAndUnBox ()
{
//
// TODO: add the constructor logic here
//
}
//////////////////////////////////////// //////////////////////////////////////// /////
Static void Main (string [] args)
{
Double dubBox = 77.77; // define a value-shaped variable
Object objBox = dubBox; // bind the variable value to a reference object.
Console. WriteLine ("The Value is {0} and The Boxed is {1}", dubBox, objBox. ToString ());
}
//////////////////////////////////////// //////////////////////////////////////// /////
}
}

In the code, we only need to pay attention to the two lines of code that are annotated under the Main () method. In the first line, we created a double type variable (dubBox ). Obviously, according to the rules, CTS requires that double is the original type, so dubBox is naturally a value type variable; the second row actually does three jobs, which will be clear in the following MSIL code. The first step is to retrieve the dubBox value, the second step is to convert the value type to the reference type, and the third step is to pass the value to the objBox.

The MSIL code is as follows:

. Method private hidebysig static void Main (string [] args) cel managed
{
. Entrypoint
// Code size 40 (0x28)
. Maxstack 3
. Locals init ([0] float64 dubBox,
[1] object objBox)
IL_0000: ldc. r8 77.769999999999996
IL_0009: stloc.0
IL_000a: ldloc.0
IL_000b: box [mscorlib] System. Double
IL_0010: stloc.1
IL_0011: ldstr "The Value is {0} and The Boxed is {1 }"
IL_0016: ldloc.0
IL_0017: box [mscorlib] System. Double
IL_001c: ldloc.1
IL_001d: callvirt instance string [mscorlib] System. Object: ToString ()
IL_0022: call void [mscorlib] System. Console: WriteLine (string,
Object,
Object)
IL_0027: ret
} // End of method BoxAndUnBox: Main

In MSIL, lines IL_0000 to IL_0010 describe the first two lines of code. Referring to the MSIL manual of C #, it is not difficult for the viewer to understand the execution process of the underlying code. Here I will describe the story of dubBox boxing: (1) dividing the stack memory, memory allocated on the stack = dubBox size + space occupied by the objBox and its structure; (2) the dubBox value (77.7699999999996) is copied to the newly allocated stack; (3) the address pressure stack assigned to objBox points to an object type, that is, the reference type.

As the inverse process of packing, unpacking seems very simple. In fact, there is a lot more to think about. First of all, explicit type conversion is not required for box, but type conversion is required for unbox. This is because objects of the reference type can be converted to any type. (Of course, this is also a manifestation of the difference between computers and the human brain) What type conversion cannot be avoided will be monitored by the CTS management center-the standard is naturally based on rules. (The content capacity is sufficient to be discussed in a specific chapter.) let's take a look at the following code:

Using System;

Namespace StructApp
{
///
/// Summary of BoxAndUnBox.
///
Public class BoxAndUnBox
{
Public BoxAndUnBox ()
{
//
// TODO: add the constructor logic here
//
}
//////////////////////////////////////// //////////////////////////////////////// /////
Static void Main (string [] args)
{
Double dubBox = 77.77;
Object objBox = dubBox;
Double dashbox = (double) objBox; // unpack the referenced object and return the value
Console. WriteLine ("The Value is {0} and The UnBoxed is {1}", dubBox, dashbox );
}
//////////////////////////////////////// //////////////////////////////////////// /////
}
}

Compared with the preceding boxed code, this Code adds a line of double d1_box = (double) objBox; the newly added code performs four tasks, which will also be reflected in the MSIL code. The first step is to press a value into the stack; the second step is to convert the reference type to the value type; the third step is to indirectly press the value to the stack; The fourth step is to pass the value to the dashbox.

The MSIL code is as follows:

. Method private hidebysig static void Main (string [] args) cel managed
{
. Entrypoint
// Code size 48 (0x30)
. Maxstack 3
. Locals init ([0] float64 dubBox,
[1] object objBox,
[2] float64 d1_box)
IL_0000: ldc. r8 77.769999999999996
IL_0009: stloc.0
IL_000a: ldloc.0
IL_000b: box [mscorlib] System. Double
IL_0010: stloc.1
IL_0011: ldloc.1
IL_0012: unbox [mscorlib] System. Double
IL_0017: ldind. r8
IL_0018: stloc.2
IL_0019: ldstr "The Value is {0} and The UnBoxe

Related Article

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: info-contact@alibabacloud.com 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.