6

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

string a = "qwer";

我需要获取的内存地址a

4

3 回答 3

6

让我们来看看你感到惊讶的情况:

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

a并且b是对字符串的引用。实际涉及的字符串是"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

比较参考文献

现在您了解a并且b是参考,您可以使用比较这些参考Object.ReferenceEquals

Object.ReferenceEquals(a, b) //true only if they reference the same exact string in memory
于 2013-09-04T12:33:06.510 回答
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 回答
0

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

于 2021-07-23T13:19:47.443 回答