Click here to Skip to main content
15,919,931 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I created an object from a class in C#. Is it possible to retrieve its memory location and address using C# code?

What I have tried:

i have tried this code but i got error at this line
IntPtr address = GCHandle.AddrOfPinnedObject(handle);
of the code

the full code is
C#
Person person_1 =  new Person("mina remon shaker");

// Get the FieldInfo for "myField"
FieldInfo? fieldInfo = typeof(Person).GetField("Name");

// Pin the object in memory (required for getting address)
GCHandle handle = GCHandle.Alloc(person_1, GCHandleType.Pinned);

// Get the address of the pinned object
IntPtr address = GCHandle.AddrOfPinnedObject(handle);

// Free the handle
handle.Free();

// "address" now points to the memory location of the entire object
// You can't directly access the address of the field within the object

Console.WriteLine("Object address: 0x{0:X}", address.ToInt64());
Posted
Comments
Pete O'Hanlon 21-May-24 16:37pm    
What error did you get?
Member 14479161 22-May-24 22:12pm    
Error CS1501 No overload for method 'AddrOfPinnedObject' takes 1 arguments C#ForBeginners D:\Projects\C#ForBeginners\C#ForBeginners\Program.cs 53 Active
Dave Kreskowiak 22-May-24 23:38pm    
That's because AddrOfPinnedObject doesn't take any arguments. When you called GCHandle.Alloc, it returns a GCHandle object, which you stored in "handle". The correct code should have been:
GCHandle handle = GCHandle.Alloc(person_1, GCHandleType.Pinned);
IntPtr address = handle.AddrOfPinnedObject();

But keep in mind, the instant you call handle.Free();, that address isn't valid anymore.
Member 14479161 25-May-24 22:32pm    
this means it is like cleard removed correct
Dave Kreskowiak 25-May-24 23:46pm    
No. Like I said before, once an object is no longer pinned, the garbage collector is free to move the object in memory any time it wants.

1 solution

Not sure why you would want to do this because the GC can move heap allocated objects around at any time, but you can do this:
C#
unsafe
{
    BaseClass baseClass = new();
    BaseClass* ptr = &baseClass;

    Console.WriteLine($"{(long)ptr:X}");
}

You need to enable unsafe code in your project properties and you're going to get a bunch of warnings about this, but the code will still compile and run.
 
Share this answer
 
Comments
Member 14479161 22-May-24 22:10pm    
I just want to experiment the heap to know how fields and method got stored in it

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900