In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article introduces the relevant knowledge of "how to understand the pointer of C# operating memory". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
C # managed code that operates memory through pointers
Generally speaking, when you write any C # program, you are creating managed code. Managed code is executed under the control of Common Language Runtime (CLR), and CLR eliminates the need for programmers to manage memory and care about memory allocation and recycling. CLR also allows you to write unsafe code (unsafe code).
C # non-secure code that operates memory through pointers
Unsafe code is code that is not executed under the full control of CLR, and it can cause problems, so they must indicate it with "unsafe":
... Unsafe {... / / unsafe context: can use pointers here...}...
The keyword 'unsafe',' can also be used in some other places, for example, we can indicate that a class or method is unsafe:
Unsafe class Class1 {} static unsafe void FastMove (int* pi, int* pdi, int length) {...}
The necessity of the unsafe' keyword is that it prevents some unexpected usage by programmers. You might ask why anyone would use it if it's not safe. The answer is that sometimes, in some cases, pointers are needed.
C # pointer to operate memory
A pointer is a special variable used to store the addresses of other variables. If you assign the addresses of * * variables to the second variable, you can say that * variables point to the second variable. CLR supports three types of pointers: managed pointers, unmanaged pointers and unmanaged function pointers. A reference to a managed block where managed pointers are stored on the heap, an unmanaged pointer is a traditional C++ pointer and must be placed in a unsafe block of code for each use, and an unmanaged function pointer is also a traditional C++ pointer to the function address (delegates can be considered an unmanaged function pointer).
You can create pointers by declaring something like this:
Type * variable _ name
Since a type can be any non-reference type and does not contain a reference type field, it can only be: sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, decimal, bool and other pointer types, or any user-defined structure that includes unmanaged type fields.
The following is an example of different types of pointer declarations:
Int* pi / / declaration a pointer to integer variable float* pf, pq / / two pointers to float variables. Not * pf, * pq char* pz / / pointer to char
As mentioned earlier, the unmanaged code CLR cannot be verified, in order to compile you need to specify the / unsafe compilation option, and if you are using Microsoft Visual Studio you need to set 'Allow unsafe code block' to True in the project options.
The basic usage of C # operating memory pointer
There are also operators that are closely related to pointers & the & operator which returns the address of the object it operates on.
For example:
Unsafe {int* pi; int x = 1; pi = & x; System.Console.WriteLine ("Value of x is:" + * pi);}
In this example, we created two variables, 'pi' is the pointer to int,' x'is int, and then we give the address of'x'in memory to 'pi', to understand that what we put in the' pi' variable is the address of'x 'instead of the value of' x'(using: pi = x will return the error "Cannot implicitly convert type 'int' to' int*'")
Execution after compilation will output:
Value of x is: 1
Pointers can accept null values or use void pointer types, and the following code compiles normally:
Unsafe {nt x = 10; void* px = & x; double* pd = (double*) px;}
Fixed keywords and garbage collection
Using pointers in C # requires more attention than in C++. This is because the garbage collector (g.c.) Memory cleanup will be run, in the process of cleaning, G.C. Will change the physical memory location of the object, if G.C. The pointer that changes the position of the object will point to the wrong memory location. To avoid this problem (already connected to the garbage collector), C # contains the 'fixed' keyword. It tells the system not to let the garbage collector redeploy the object.
'fixed' example:
/ / pt is a managed variable, subject to g.c. Colour cl = new Colour (); / / must use fixed to get address of cl.R fixed (int* pi = & cl.R) {* pi = 1;}
Initialize multiple pointers of the same type:
Fixed (byte* pb = sarr, pd = darr) {.}
C # operation memory initialization of different types of pointers:
Fixed (int* pi = & cl.G) fixed (double* pd = & array [10])
If we forget the 'fixed' keyword compiler will give us a warning, but it is not smart enough to warn us in the following situations. The following code has a serious Bug although the compilation is normal.
Class Test {public int x;} unsafe class SimpleTest {[STAThread] static void Main (string [] args) {Test test = new Test (); int* pi; fixed (int* px = & test.x) {* px = 100; pi = px;} Console.WriteLine ("before g.c.:" + * pi); System.GC.Collect (2); Console.WriteLine ("after g.c.:" + * pi);}}
On my machine, it turns out:
Before g.c.: 100 after g.c.: 132
We can see that the same pointer has two different values, in fact, in 'before g.c.' And 'after g.c.' The chances of getting different results are very small, because probability of starting garbage collector is very little. But as a rule, we should avoid using pointers outside of fixed blocks. In our case, every time we use 'pi' pointers outside of fixed blocks, it is possible to produce errors that are difficult to diagnose.
C # operating memory pointer and WinApi
The most important benefit of using pointers is that you can interact with other binaries. Many WinApi functions use pointers, such as GetComputerName (Kernel32.lib.) You can provide the name of our computer.
BOOL GetComputerName (LPTSTR lpBuffer, / / computer name LPDWORD lpnSize / / size of name buffer)
The following program demonstrates how to use GetComputerName:
[System.Runtime.InteropServices.DllImport ("Kernel32")] static extern unsafe bool GetComputerName (byte* lpBuffer,long* nSize); static void Main () {byte [] buffor = new byte; long size = buffor.Length; unsafe {long* pSize = & size; fixed (byte* pBuffor = buffor) {GetComputerName (pBuffor,pSize);}} System.Text.Encoding textEnc = new System.Text.ASCIIEncoding () System.Console.WriteLine ("Computer name: {0}", textEnc.GetString (buffor);}
C # operating memory conclusion
We have seen that pointers are a very useful part of the C# language, it is not difficult to use pointers, but be very careful, because it may lead to problems that are difficult to diagnose, and using pointers can disrupt the function of the garbage collector. especially when we use pointers a lot in the program. So we should think more about it before using the pointer, or try other solutions.
This is the end of the content of "how to understand the pointer of C# operating memory". Thank you for your reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.