If I manipulate a managed C# string in place (for example, reverse its characters) by using pointers in an unsafe code block or method, can that unsafe implementation confuse or corrupt the .NET string pooling mechanisms?

The proposed string being manipulated is created in managed code and passed to an unsafe method to be manipulated.

Example of this scenario:

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;
        }
    }
}
有帮助吗?

解决方案

Sure. Just write it like this to see the damage:

    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!

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top