Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# memory address and variable

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:

int i;
int* pi = &i;
  • How do you print out the hex value of pi?
like image 475
Ray Lu Avatar asked Sep 08 '25 14:09

Ray Lu


1 Answers

For #2, the & operator will work in the same fashion as in C. If the variable is not on the stack, you may need to use a fixed statement to pin it down while you work so the garbage collector does not move it, though.

For #1, reference types are trickier: you'll need to use a GCHandle, and the reference type has to be blittable, i.e. have a defined memory layout and be bitwise copyable.

In order to access the address as a number, you can cast from pointer type to IntPtr (an integer type defined to be the same size as a pointer), and from there to uint or ulong (depending on the pointer size of the underlying machine).

using System;
using System.Runtime.InteropServices;

[StructLayout(LayoutKind.Sequential)]
class Blittable
{
    int x;
}

class Program
{
    public static unsafe void Main()
    {
        int i;
        object o = new Blittable();
        int* ptr = &i;
        IntPtr addr = (IntPtr)ptr;

        Console.WriteLine(addr.ToString("x"));

        GCHandle h = GCHandle.Alloc(o, GCHandleType.Pinned);
        addr = h.AddrOfPinnedObject();
        Console.WriteLine(addr.ToString("x"));

        h.Free();
    }
}
like image 84
Jeffrey Hantin Avatar answered Sep 10 '25 09:09

Jeffrey Hantin