簡體   English   中英

如何在C#中獲取字符串的內存地址?

[英]How to get the memory address of a string in C#?

有人可以告訴我在 C# 中獲取string內存地址的方法嗎? 例如,在:

string a = "qwer";

我需要的內存地址a

您需要使用 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**

讓我們來看看你感到驚訝的情況:

string a = "abc";
string b = a;
a = "def";
Console.WriteLine(b); //"abc" why?

ab是對字符串的引用。 實際涉及的字符串是"abc""def"

string a = "abc";
string b = a;

ab都是對同一個字符串"abc"引用。

a = "def";

現在a是對新字符串"def"的引用,但我們沒有做任何更改b ,因此它仍然引用"abc"

Console.writeline(b); // "abc"

如果我對整數做了同樣的事情,你不應該感到驚訝:

int a = 123;
int b = a;
a = 456;
Console.WriteLine(b); //123

比較參考

現在您了解ab是引用,您可以使用Object.ReferenceEquals比較這些引用

Object.ReferenceEquals(a, b) //true only if they reference the same exact string in memory

您可以調用 RtlInitUnicodeString。 該函數返回字符串的長度和地址。

using System;
using System.Runtime.InteropServices;

class Program
{
    [StructLayout(LayoutKind.Sequential)]
    public struct UNICODE_STRING
    {
      public ushort Length;
      public ushort MaximumLength;
      public IntPtr Buffer;
    }

  [DllImport("ntdll.dll", CharSet = CharSet.Unicode)]
  static extern void RtlInitUnicodeString(out UNICODE_STRING DestinationString, string SourceString);

  [STAThread]
  static void Main()
  {
    UNICODE_STRING objectName;

    string mapName = "myMap1";
    RtlInitUnicodeString(out objectName, mapName);

    IntPtr stringPtr1 = objectName.Buffer;   // address of string 1


    mapName = mapName + "234";
    RtlInitUnicodeString(out objectName, mapName);

    IntPtr stringPtr2 = objectName.Buffer;  // address of string 2
  }
}

了解 C# 如何管理字符串會很有用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM