如果我通过在不安全的代码块或方法中使用指针来操作托管的C#字符串(例如,反转其字符),那么不安全的实现是否会混淆或破坏.NET字符串池机制?
正在操作的建议字符串是在托管代码中创建的,并传递给不安全的方法进行操作.
此方案的示例:
static void Main(string[] args) {
string s = "this is a test";
UnsafeReverse(s);
Console.WriteLine(s); // displays "tset a si siht"
// assume more managed strings are created and used along with the affected s.
}
static unsafe void UnsafeReverse(string str) {
int len = str.Length;
fixed (char* pStr = str) {
char* p1 = pStr;
char* p2 = pStr + len - 1;
char tmp;
while (p1 < p2) {
tmp = *p1;
*p1 = *p2;
*p2 = tmp;
++p1; --p2;
}
}
}
解决方法:
当然.只需这样写它就可以看到损坏:
static readonly string DontMessWithStrings = "this is a test";
static void Main(string[] args) {
string s = "this is a test";
UnsafeReverse(s);
Console.WriteLine(DontMessWithStrings);
}
[Edit by OP] The result of displaying
DontMessWithStrings
is “tset a
si siht” even though that variable is never directly touched by the string manipulation code!