Is it possible to get a string representation of the address of a C # object?

I'm trying to debug some strange multithreaded code behavior, and I need to somehow reliably track the identity of the object. In C ++, I just get the addresses of objects and convert them to strings, and so I would know if two addresses have the same object or not.

The link seems to be the full equivalent of the address of a C ++ object in C #.

Can I convert a link to a string address representation?

+4
source share
3 answers

You can convert the link to a pointer and then to a number, but this is not a reliable way to track an object in C #, since the garbage collector can change the link at any time. Once you copy the value from the link, you may not know that it still represents the link.

However, you can safely compare the links. As long as the link is still a link, the garbage collector ensures that it is updated. If the garbage collector moves an object, it updates all references to it.

That way, you can safely use the link as an identifier for an object if you hold it with a link. You can compare the two links to see if they point to the same object or not.

If you convert the link value to another form, you get a copy of the flash copy of what the link was at that moment. Although it may be useful to see this value, it is not 100% reliable, i.e. Just because the presentation of the two links is different does not mean that they cannot point to the same object, since the links can be changed between copying the first and second.

So here is how you can get a pointer to an object and convert it to IntPtr :

 string str = "asdfasdf"; IntPtr p; unsafe { // tell GC not to move the object, so that we can use a pointer to it fixed (void* ptr = str) { // here the object stays in place // make an IntPtr from the pointer, so we can keep it outside the fixed block p = new IntPtr(ptr); } // now the object can move again } Console.WriteLine(p); 
+3
source

In a sense, you can:

 GCHandle.Alloc(obj, GCHandleType.Pinned).AddrOfPinnedObject().ToString(); 

Please do not use this as a way to debug your multi-threaded application. Do as Damien pointed out.

0
source

Create a ConditionalWeakTable<Object,String> , and every time you see that every object that is not in the table gives it some name and stores it in the table. Then you can easily print the name for any object that you saw, just using the table. If the object ceases to exist, the entry in the table will evaporate, so there is no need to worry about the fact that the table is filled with information related to objects that have long been left behind.

0
source

Source: https://habr.com/ru/post/1444289/


All Articles