Reputation: 16219
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?
Upvotes: 4
Views: 18874
Reputation: 5688
Unsafe code. Compile with /unsafe (checkbox in the VS project properties)
unsafe
{
fixed(MyobjType* objptr = &myobj)
{
// do sthng
}
}
Upvotes: 1
Reputation: 26446
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.
Upvotes: 4