获取.NET对象的内存地址(C#) [英] Get Memory Address of .NET Object (C#)

查看:1169
本文介绍了获取.NET对象的内存地址(C#)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图追查在一个变量似乎分配给一个有效的对象的单声道运行时的错误,然后再重新分配给一个假的对象,特别是

I am trying to track down a bug in the mono runtime where a variable appears to be allocated to one valid object, and then is reassigned later to a bogus object, specifically

//early in code I allocate, fine
var o = new object(); // valid allocation
// later in code this is called, not fine
lock(o) // <- is triggering bug due to "o" now referencing a nonsense memory location.



我想知道,当提及O变得毫无意义,这样做很期待换一种方式来确定O在C#代码中的不同时间点的地址。我知道类似的答案其他问题不这样做,有一个GC,但GC没有工作,所以我需要一个解决办法。

I would like to know when the reference to "o" becomes nonsense, and to do this am looking for a way to determine the address of "o" at various timepoints within the C# code. I know is similar to other questions with answers "don't do that there is a GC", but the GC doesn't work so I need a workaround.

请问任何人都知道我怎么能确定在C#中单对象的地址?我很好在非托管代码或任何链接。 (任何其他线索的方法来诊断的主要问题赞赏)。

Does anyone know how I can determine the address of a mono object in C#? Am fine to link in unmanaged code or whatever. (Any other clues to ways to diagnose the main issue appreciated to).

推荐答案

原来,这直接是不可能的。NET的,但可以通过改变单运行时代码来实现。要创建可读取内存地址,进行以下修改单源代码的C#方法:

Turns out this is not possible in .NET directly, but can be accomplished by altering the mono runtime code. To create a C# method that can read the memory address, make the following changes to the mono source code:

阿尔特GC-internal.h添加

Alter gc-internal.h to add

gpointer    ves_icall_System_GCHandle_GetAddrOfObject (MonoObject *obj) MONO_INTERNAL;



ALTER gc.c补充:

Alter gc.c to add:

gpointer    ves_icall_System_GCHandle_GetAddrOfObject (MonoObject *obj) {
    return (char*)obj;
}



阿尔特GCHandle.cs补充:

Alter GCHandle.cs to add:

MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern static IntPtr GetAddrOfObject(object obj);

public static IntPtr AddrOfObject(object o)
{
    IntPtr res = GetAddrOfObject(o);
    return res;
}



阿尔特ICALL-def.h添加

Alter icall-def.h to add

ICALL(GCH_6, "GetAddrOfObject", ves_icall_System_GCHandle_GetAddrOfObject)

请注意,这些必须是为了,所以加在它上面的GetAddrOfPinnedObject线
重建

Note that these must be in order, so add it above the GetAddrOfPinnedObject line Rebuild

最后,从C#调用它

for (int i = 0; i < 100; i++) {
    object o = new object ();
    var ptr = GCHandle.AddrOfObject (o);
    Console.WriteLine ("Address: " + ptr.ToInt64().ToString ("x"));
}

这篇关于获取.NET对象的内存地址(C#)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆