Reputation: 3616
In C#
how can you get the address of a variable without using the unsafe
keyword.
I do not want to change the address or access it, just have its location.
Upvotes: 2
Views: 4692
Reputation: 48949
You will have to pin the object before extracting its address. Otherwise, the GC is free to move it around.
object variable = new object();
GCHandle handle = GCHandle.Alloc(variable, GCHandleType.Pinned);
IntPtr address = handle.AddrOfPinnedObject();
Normally you would only do this in scenarios requiring some type of unmanaged interop. However, even then there is rarely a need for this type of manual manipulation.
Upvotes: 4
Reputation: 152566
Since .NET moved variables in managed memory around all the time, you need to "pin" the variable, then get its location with GCHandle
:
static void Main()
{
string myVar = "This is my string";
GCHandle handle = GCHandle.Alloc(myVar, GCHandleType.Pinned);
IntPtr pointer = GCHandle.ToIntPtr(handle);
Console.WriteLine(pointer);
handle.Free();
}
However, I believe this actually moves the original variable to a new location referenced by the GCHandle
, and it doesn't work for all types - only blittable types.
Upvotes: 7
Reputation: 174329
You can't.
And for good reason, because the address is not fixed. It can - and will - be moved around by the memory management of the CLR.
Upvotes: 17