繁体   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