C USES unmanaged code to modify strings directly

  • 2020-05-17 06:14:21
  • OfStack


using System; 
public class Test
{
 public static void Main(string[] args)
 {
  string str = "hello";
  ToUpper(str);
  Console.WriteLine(str);
 }
 private static unsafe void ToUpper(string str)
 {
  fixed(char * pfixed = str)
  for(char * p=pfixed;*p!=0;p++)
  {
   *p = char.ToUpper(*p);
  }
 }
}

fixed statements:
Format fixed (type* ptr = expr) statement
Its purpose is to prevent variables from being located by the garbage collector.
Among them:
type is an unmanaged type or void
ptr is the pointer name
expr is an expression that can be implicitly converted to type*
statement is an executable statement or block
The fixed statement, which can only be used in the context of unsafe, sets a pointer to a managed variable and "locks" it during the execution of statement. Without an fixed statement, Pointers to managed variables are of little use, because garbage collection can unpredictably relocate variables.
After the execution of statement, any locked variables are unlocked and subject to garbage collection. Therefore, do not point to variables outside of the fixed statement. In insecure mode, memory can be allocated on the stack. The stack is not subject to garbage collection and therefore does not need to be locked.

At compile time, however, you must use /unsafe to pass because you are using unmanaged code.


Related articles: