C# memory address and variable

后端 未结 3 1884
春和景丽
春和景丽 2020-11-28 09:45

in C#, is there a way to

  1. Get the memory address stored in a reference type variable?
  2. Get the memory address of a variable?

EDIT:

3条回答
  •  鱼传尺愫
    2020-11-28 10:22

    Number 1 is not possible at all, you can't have a pointer to a managed object. However, you can use an IntPtr structure to get information about the address of the pointer in the reference:

    GCHandle handle = GCHandle.Alloc(str, GCHandleType.Pinned);
    IntPtr pointer = GCHandle.ToIntPtr(handle);
    string pointerDisplay = pointer.ToString();
    handle.Free();
    

    For number 2 you use the & operator:

    int* p = &myIntVariable;
    

    Pointers of course have to be done in a unsafe block, and you have to allow unsafe code in the project settings. If the variable is a local variable in a method, it's allocated on the stack so it's already fixed, but if the variable is a member of an object, you have to pin that object in memory using the fixed keyword so that it's not moved by the garbage collector.

提交回复
热议问题