6

誰かがstringC# で a のメモリ アドレスを取得する方法を教えてもらえますか? たとえば、次のようになります。

string a = "qwer";

のメモリアドレスを取得する必要がありますa

4

3 に答える 3

6

fixed キーワードを使用してメモリ内の文字列を修正し、char* を使用してメモリ アドレスを参照する必要があります。

using System;

class Program
{
    static void Main()
    {
        Console.WriteLine(Transform());
        Console.WriteLine(Transform());
        Console.WriteLine(Transform());
    }

    unsafe static string Transform()
    {
        // Get random string.
        string value = System.IO.Path.GetRandomFileName();

        // Use fixed statement on a char pointer.
        // ... The pointer now points to memory that won't be moved!
        fixed (char* pointer = value)
        {
            // Add one to each of the characters.
            for (int i = 0; pointer[i] != '\0'; ++i)
            {
                pointer[i]++;
            }
            // Return the mutated string.
            return new string(pointer);
        }
    }
}

出力

**61c4eu6h/zt1

ctqqu62e/r2v

gb{kvhn6/xwq**

于 2013-09-04T12:27:58.860 に答える