C#如何获得引用类型在内存中的地址

maladoufu 2012-12-10 06:04:15
在unsafe代码断中,通过&只能获得值类型在内存中的地址,如MSDN中给出的代码断:

class AddressOfOperator
{
static void Main()
{
int number;

unsafe
{
// Assign the address of number to a pointer:
int* p = &number;

// Print the value of *p:
System.Console.WriteLine("Value at the location pointed to by p: {0:X}", *p);

// Print the address stored in p:
System.Console.WriteLine("The address stored in p: {0}", (int)p);
}

System.Console.ReadKey();
}
}

可是引用类型,比如string,声明string类型的指针时会报错:
无法获取托管类型(“string”)的地址和大小,或无法声明指向它的指针
请指教引用类型的地址要怎么样才能取到?
多谢各位~
...全文
1234 12 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
12 条回复
切换为时间正序
请发表友善的回复…
发表回复
子兮、 2014-11-25
  • 打赏
  • 举报
回复
原文参见:http://stackoverflow.com/questions/588817/c-sharp-memory-address-and-variable
子兮、 2014-11-25
  • 打赏
  • 举报
回复
using System; using System.Runtime.InteropServices; [StructLayout(LayoutKind.Sequential)] class Blittable { int x; } class Program { public static unsafe void Main() { int i; object o = new Blittable(); int* ptr = &i; IntPtr addr = (IntPtr)ptr; Console.WriteLine(addr.ToString("x")); GCHandle h = GCHandle.Alloc(o, GCHandleType.Pinned); addr = h.AddrOfPinnedObject(); Console.WriteLine(addr.ToString("x")); h.Free(); } }
西伯利亚Wolf 2013-05-10
  • 打赏
  • 举报
回复
你现在搞定怎么获取引用类型变量的地址了么? 我也想知道下
  • 打赏
  • 举报
回复
IntPtr p = System.Runtime.InteropServices.StringToHGlobalAnsi("abc");
maladoufu 2012-12-12
  • 打赏
  • 举报
回复
引用 7 楼 wangyue4 的回复:
GcHandle应该可以,可是你拿这个地址没有意义啊,引用类型内存的地址会变化的
“引用类型内存的地址会变化的”,这个会吗? “所有引用类型的实例(对象、值)都是创建在堆上的,而这个为变量分配的内存就存放变量对应在堆上的实例(对象、值)的内存首地址(内存指针)”实例化对象之后在内存中的地址是固定的吧,知道被GC回收之前,我是这么理解的 ~anyway 我还是没取到。再UP最后一次
maladoufu 2012-12-11
  • 打赏
  • 举报
回复
开发环境 : Visual Studio 2012 语言:C# 目的:获得引用类型(如String)在内存中的存储地址 求指点~~
maladoufu 2012-12-11
  • 打赏
  • 举报
回复
引用 4 楼 yuwenge 的回复:
char *
不行的, Struct System.Char 是值类型, char* 不能指向引用类型String的地址
卧_槽 2012-12-11
  • 打赏
  • 举报
回复
char *
maladoufu 2012-12-11
  • 打赏
  • 举报
回复
引用 2 楼 mefrender 的回复:
引用类型就是指针。直接取值。


- -
string str;
&str;

这样吗,不行啊,

我是想获取引用类型在内存中的地址 比如 通过ref str可以传递地址,但是怎么样知道这个地址的内容呢
mefrender 2012-12-11
  • 打赏
  • 举报
回复
引用类型就是指针。直接取值。
maladoufu 2012-12-11
  • 打赏
  • 举报
回复
help ...
大黄鸭在发光 2012-12-11
  • 打赏
  • 举报
回复
GcHandle应该可以,可是你拿这个地址没有意义啊,引用类型内存的地址会变化的

111,094

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • AIGC Browser
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧