Recently, we have been porting Fortran to C #. net, because Fortran is a language used for scientific computing, which uses a large number of arrays and most of its operations are read and write operations on arrays. And familiar. net Framework people know that when we access the elements in the array, CLR will first check whether the index has exceeded the upper and lower bounds of the array. if it exceeded, System will be thrown. indexOutOfRangeException exception. It is precisely because of this "nanny program" that the. NET program will inevitably have some performance costs for Array Operations. What we need to do today is to directly skip this layer of "nanny program" and use pointers to directly operate the elements in the array.
To use pointers in programs, we need to mark unsafe code and use special keywords unsafe.
Unsafe code is a type of code between hosted code and unmanaged code. It can be executed under the management of CLR like hosted code, it also allows you to use pointers to directly operate on memory like an unmanaged code. Specifically, all statements, statement blocks, or functions that use any of the pointer operators commonly used in C language are called Unsafe code.
Example:
Unsafe void SquarePtrParam (int * p)
{
* P * = * p;
}
To avoid Memory leakage, we need to enter the keyword fixed before the statement block (its function is to prohibit the garbage collector from relocating movable variables) to tell CLR that the objects or variables in the statement block cannot be relocated.
The specific implementation process is as follows:
Set compiler options in the development environment: Open the "properties" page of the project --> click "generate" --> select the "allow unsafe code" check box
The feasible instance code is as follows:
Public class QuikeArrayRead
{
Unsafe void SquarePtrParam (int * p)
{
* P * = * p;
}
Public unsafe void run ()
{
Int [] arr = new int [] {1, 2, 3, 4, 5 };
Fixed (int * p = & arr [0])
{
For (int I = 0, n = arr. Length; I <n; I ++)
{
SquarePtrParam (p + I );
Console. WriteLine (p [I]);
}
}
}
}