Key: unsafe, fixed in C)

Source: Internet
Author: User
The original address http://www.cppblog.com/mzty/archive/2006/03/14/4126.html this article will discuss how to use pointers in C.

Introduction
This is C/C ++ProgramA topic that fans often talk about is also a complicated and hard-to-understand topic-pointer! Every time I talk about C #, most people I come across share this idea-C # has no pointer. In fact, it has been abolished and replaced by non-secure programming in C #-how to use pointers in programs. Unlike its literal meaning, it is safe to use pointer programming.
The root cause of this concern is that non-secure programming is different from the customary. NET development specification and requires programmers to explicitly set the local environment (only applicable to local execution ). In this article, I will distinguish two concepts that are the easiest to be confused-non-securityCodeStart to discuss the topic of unsafe programming with uncontrolled code. Next we will discuss how to write non-secure code, that is, how to use pointers in C.

Unsecure or uncontrolled?

Controlled Code refers to the Code executed under the CLR management. CLR is responsible for a lot of behind-the-scenes work:

    • Manage Object Memory
    • Type Verification
    • Garbage Collection

After talking about this, we need to free users from the above work and concentrate on business implementation. You no longer need to perform manual memory operations because these operations have been completed by CLR.
On the other hand, uncontrolled code is the code executed outside the CLR context. The best example is the Win32 DLL we usually use, such as kernel32.dll, user32.dll, and various COM components installed on our system. How to allocate memory for them, how to release these memories, and how to implement type verification? These tasks must be completed by themselves. The assignment of a character pointer to a typical C ++ program is another example of uncontrolled code, because as a programmer, you are responsible:

    • Call the Memory Allocation Function
    • Make sure that the type conversion result is correct.
    • Make sure that the memory of the pointer is released after use.

If you pay attention to the above explanation, all this work is done by CLR to reduce the burden on programmers.

Unsafe code is a type of code between controlled and uncontrolled code.

Unsafe code is still executed under CLR management like controlled code, but it also allows you to directly access the memory through pointers like uncontrolled code. Therefore, you have obtained the advantages of both. If you are writing a. NET application, but want to use a wide range of functions in Win32 DLL-you need to use pointers, then the unsecure code is your savior.
We have already clarified the differences between the two and started to write the actual code. Without a doubt, this is the most exciting part. What are you still thinking about?

In-depth non-security code
Special keywords are required for writing Unsafe code.UnsafeAndFixed. If you still remember, there are three pointer operators:

    • *
    • &
    • ->

Any statement, block, or function that uses any of the above pointer operators is applied.UnsafeThe keyword is marked as a non-secure code, just like this:

 
Public unsafe void triple (int * pint) {* pint = (* pint) * 3 ;}

The above function only doubles the value of the input parameter. However, please note that the pointer to this parameter is passed in! Because this function uses the "*" operator to perform memory operations directly, it is markedUnsafe.
But there is still a problem here. Looking back at the above discussion, Unsafe code is also controlled code under CLR management, and CLR can freely move objects into memory. Therefore, a plausible cause may cause memory leakage. The result is that programmers may unconsciously direct the pointer of this variable to other places in the memory.
Therefore, assume that * pint points to 1001, and CLR memory relocation will cause memory leakage. Point to 1001 before pint, and the data it points to after relocation may be stored at Address 2003. This is the cause of the disaster! Pint points to 1001 of the stored data after the relocation process is invalid. This may be why. Net seldom mentions pointer usage. What do you think?

Fixed pointer
Enter keywords before statement BlocksFixedWill tell the CLR block that the object cannot be relocated, so that the CLR will not relocate the data storage location pointed to by the pointer. Therefore, when using pointers in C #, use keywordsFixedIt will prevent invalid pointers from being generated when the program is running. Let's see how it works:

Using system; Class CDATA {public int X;} class cprogram {unsafe static void setval (int * pint) {* pint = 1979;} public unsafe static void main () {CDATA d = new CDATA (); console. writeline ("previous value: {0}", D. x); fixed (int * P = & D. x) {setval (p);} console. writeline ("New Value: {0}", D. x );}}

In this Code, a fixed block is used to assign the address of CDATA object data member (domain) X to an integer pointer p. When the statement in the fixed block is executed, the pointer P will always point to the original memory area, because CLR has been instructed to temporarily freeze the variable until the execution of the fixed block is complete. Once the fixed block is executed, the object can be located again by CLR.
The above is the introduction of using pointer programming in C #. The key is to note that the statement block is unsafe and fixed. Hope to improve your knowledge of pointer usage in C!

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.