如何在 C# 中获取字符串的内存地址

本文关键字:字符串 内存 地址 获取 | 更新日期: 2023-09-27 18:30:17

有人可以告诉我在 C# 中获取string内存地址的方法吗?例如,在:

string a = "qwer";

我需要获取a的内存地址。

如何在 C# 中获取字符串的内存地址

您需要使用

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"

如果我对 ints 做了同样的事情,你不应该感到惊讶:

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# 如何管理字符串可能很有用。