如何在C#中显示指针地址?

22

自从我开始使用C#编程以来,我就没有使用过指针 - 而我的C++时代已经很久远了。我想我应该刷新一下我的知识,并且只是因为这里的另一个问题而玩弄它们。我都能理解它们,但我无法弄清楚如何将指针地址写入控制台...

char c = 'c';
char d = 'd';
char e = 'e';

unsafe
{
    char* cp = &d;
    //How do I write the pointer address to the console?
    *cp = 'f';
    cp = &e;
    //How do I write the pointer address to the console?
    *cp = 'g';
    cp = &c;
    //How do I write the pointer address to the console?
    *cp = 'h';        
}
Console.WriteLine("c:{0}", c); //should display "c:h";
Console.WriteLine("d:{0}", d); //should display "d:f";
Console.WriteLine("e:{0}", e); //should display "e:g";

使用 Console.WriteLine(*cp); 可以输出指针地址上的当前值,但如果我想显示实际地址怎么办?


你尝试过Console.WriteLine(cp);这段代码吗?它会输出什么结果呢? - Lazarus
@Lazarus - 你不认为这是我尝试的第一件事吗?哈哈,给我点信任,我在来这里问问题之前已经尝试了所有明显的方法;) - BenAlabaster
5个回答

28
Console.WriteLine(new IntPtr(cp));

为了在C#中正确地使用指针,请使用IntPtr类。 - Oliver

4

请记住,使用托管代码时,垃圾回收器可以自由地对其进行移动。 如果您处于地址相关的情况下,请确保将对象固定(pin)在原处。


1
char c = 'c';

unsafe
{
  Console.WriteLine("0x{0:x}", (ulong)&c);
  Console.WriteLine($"0x{(ulong)&c:x}");
}

这将显示类似于... 0x123abc(两次)的内容。

1
char* cptr;
char achr = 'a';
cptr = &achr;
string strcptr = Convert.ToString((long)cptr, 16);
Console.WriteLine("Ox{0} is the char ptr hex address", strcptr);

0

将您的指针转换为字节类型。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接