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

时间:2013-09-04 12:05:57

标签: c#

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

string a = "qwer";

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

3 个答案:

答案 0 :(得分:6)

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

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

答案 1 :(得分:5)

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

答案 2 :(得分: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# 如何管理字符串会很有用。