4

How can I get address of an object in c#?

i searched and found

GCHandle handle = GCHandle.Alloc(obj, GCHandleType.WeakTrackResurrection);

int address = GCHandle.ToIntPtr(handle).ToInt32();

But need some more simple code

Is & operator can used here?

Neo
  • 15,491
  • 59
  • 215
  • 405
  • 7
    I know I'll regret asking, but why do you need the address of a C# object? – Mitch Wheat Sep 14 '11 at 10:25
  • 1
    The real question is what do you plan to do with the address of an object in C# ? – Roee Gavirel Sep 14 '11 at 10:25
  • Getting the address of an arbitrary object in .NET is not possible, but can be done if you change the source code and use mono. See instructions here: http://stackoverflow.com/questions/25410158/get-memory-address-of-net-object-c/25432952#25432952 – evolvedmicrobe Aug 21 '14 at 18:00

2 Answers2

4

Objects by default don't have a fixed address in C#, you'll need to explicitly tell the garbage collector to pin it.

See http://geekswithblogs.net/robp/archive/2008/08/13/speedy-c-part-3-understanding-memory-references-pinned-objects-and.aspx for a detailed description.

C.Evenhuis
  • 25,996
  • 2
  • 58
  • 72
1

Unsafe code. Compile with /unsafe (checkbox in the VS project properties)

unsafe
{
    fixed(MyobjType* objptr = &myobj)
    {
      // do sthng
    }
}
Olivier
  • 5,578
  • 2
  • 31
  • 46
  • 1
    This generates error like: Cannot take the address of, get the size of, or declare a pointer to a managed type ('object') – Peteter Nov 12 '13 at 10:08
  • @Peteter Only works with structs. see http://msdn.microsoft.com/en-us/library/75dwhxf7.aspx – Olivier Nov 12 '13 at 10:17