. Net (C #): Write pointer operation code similar to C/C ++ in three ways

Source: Internet
Author: User

Try to write the following C/C ++ pointer operation code in three. Net methods. Note that all. Net methods do not directly reference external function resources (dllimport). They are all provided by the. NET ecosystem.

Note: All code outputs only represent the running results in the 32-bit and little-Endian CPU environments.

 

Let's take a look at this typical C/C ++ pointer operation code:

/****************************

* C/C ++ code

****************************/

Int I = 0xaa00ff;

// I memory storage format: ff 00 AA 00

Unsigned char * P = (unsigned char *) & I;

For (INT I = 0; I <sizeof (I); I ++)

Cout

// Line feed

Puts ("");

// Output: ff 00 AA 00

// Note the position of P after the loop. The P-3 points to the second byte of variable I in the memory.

* (P-3) = 0xcc;

// Current memory storage format: ff cc aa 00

// I is changed to xaaccff = 11193599

Cout <dec <I <Endl;

// Output: 11193599

 

The logic annotation is clearly explained. The above code will output:

Ff 00 AA 00

11193599

 

The execution of. Net (C #) requires the logic and output to be the same as the above Code!

Note:

Because the. NET Object Memory Distribution is different from that of the unmanaged C/C ++, not all types can do this.

 

 

Directory

  • 1. directly operate the managed heap: Buffer class
  • 2. Unmanaged heap: Marshal class
  • 3. Managed function Stack: unsafe and stackalloc keywords

 

 

Returned directory

1. directly operate the managed heap: Buffer class

This is amazing. You can do this directly in the hosting heap. In short, the buffer class operates the original data type in the form of continuous byte streams. The above C/C ++ code can be easily implemented using the getbyte and setbyte methods.

/****************************

* C # code (managed heap: Buffer class)

****************************/

 

Int [] arr = new int [] {0xaa00ff };

// Memory storage format: ff 00 AA 00

For (INT I = 0; I <sizeof (INT); I ++)

{

Console. Write ("{0: X2}", buffer. getbyte (ARR, I ));

}

// Line feed

Console. writeline ();

 

Buffer. setbyte (ARR, 1, 0xcc );

// Change to: ff cc aa 00

// Arr [0] = 0 xaaccff = 11193599

Console. writeline (ARR [0]);

The logic is the same as the output!

 

 

Returned directory

2. Unmanaged heap: Marshal class

Next, use the platform or com to call the commonly used Marshal class (within the namespace of system. runtime. interopservices ). It is mainly used to encapsulate and process environment objects in unmanaged calls.

 

Therefore, to process the data of our program, we need to first create this data in the unmanaged environment, first use the allochglobal method of the marshal class, this method calls the localalloc function of kernel32.dll, in this way, the memory is allocated in the process's unmanaged heap. Then you can use the readxxx and writexxx methods of the marshal class to perform data operations. Finally, do not forget to manually release resources in the unmanaged heap!

Code:

/***************************

* C # code (unmanaged heap: Marshal class)

***************************/

 

// + Using system. runtime. interopservices;

 

// Allocate space

VaR P = marshal. allochglobal (4 );

// Assign a value

Marshal. writeint32 (p, 0xaa00ff );

 

// Memory storage format: ff 00 AA 00

For (INT I = 0; I <marshal. sizeof (typeof (INT); I ++)

{

Console. Write ("{0: X2}", Marshal. readbyte (P, I ));

}

// Line feed

Console. writeline ();

 

// Change to: ff cc aa 00

// P = 0 xaccff = 11193599

Marshal. writebyte (P, 1, 0xcc );

 

Console. writeline (marshal. readint32 (p ));

 

// Clear Resources in the unmanaged heap

Marshal. freehglobal (P );

Similarly, the logic is the same, and the output is the same.

 

 

Returned directory

3. Managed function Stack: unsafe and stackalloc keywords

In fact, this is the way most people think of using C # To write code similar to pointers. Here the unsafe keyword is required. Stackalloc declares an array on the local function stack for demonstration purposes only.

The disadvantage of this method is that the Unsafe code must be used.

Advantage: pointer logic code is too similar to C/C ++. Second, stackalloc declares that the array space is in the stack, which is very efficient and reduces the GC pressure.

 

Code:

// Mark the unsafe keyword. Compiling requires Visual Studio to allow Insecure code or CSC unsafe Parameters

Unsafe static void main ()

{

/***************************

* C # code (function Stack: Unsafe code)

***************************/

 

// Allocate space

// Directly declare the variable here.

// For example only, we package the variables in the array!

// Note that the array here is not in the heap, but in the local function stack!

Int * arr = stackalloc int [1];

* Arr = 0xaa00ff;

 

// Pointer

Byte * P = (byte *) Arr;

 

// Memory storage format: ff 00 AA 00

For (INT I = 0; I <marshal. sizeof (typeof (INT); I ++)

{

Console. Write ("{0: X2}", (INT) (* P ++ ));

}

// Line feed

Console. writeline ();

 

// Change to: ff cc aa 00

// P = 0 xaccff = 11193599

* (P-3) = 0xcc;

 

Console. writeline (* ARR );

 

}

The same logic and output are the same as the C/C ++ code!

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.