C#使用非托管代码直接修改字符串的方法
程序员文章站
2023-12-20 13:15:52
复制代码 代码如下:using system; public class test{ public static void main(string[] args)...
复制代码 代码如下:
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语句:
格式 fixed ( type* ptr = expr ) statement
它的目的是防止变量被垃圾回收器生定位。
其中:
type为非托管类型或void
ptr为指针名
expr为可以隐式转换为type*的表达式
statement为可执行的语句或块
fixed语句只能在unsafe的上下文中使用,fixed 语句设置指向托管变量的指针并在 statement 执行期间“锁定”该变量。如果没有 fixed 语句,则指向托管变量的指针将作用很小,因为垃圾回收可能不可预知地重定位变量。
执行完 statement 后,任何锁定的变量都被取消锁定并受垃圾回收的制约。因此,不要指向 fixed 语句之外的那些变量。在不安全模式中,可以在堆栈上分配内存。堆栈不受垃圾回收的制约,因此不需要被锁定。
但在编译时,因为使用了非托管代码,必须要使用/unsafe才能通过。