如果我通过在不安全的代码块或方法中使用指针来操作托管的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!
标签:c,clr,unsafe,string 来源: https://codeday.me/bug/20190529/1178213.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。