Search code examples
c#pointersunsafe

(C#) Convert int type to address type


I can compile a code like this

unsafe static void Main()
{
  int i = 5;
  int* j = &i;
}

But how can I convert address type to int type and vice versa? like:

unsafe static void Main()
{
  int i = 5;
  int _j = (int)&i;
  int* j = (AddressType)_j;
}

Solution

  • Without knowing what you are tying to achieve; you'd have to cast that to int before you could get pointer. But that is a pointer to a pointer address.

        enum AddressType
        {
            a,
            b,
            c,
            d,
            e
        }
        unsafe static void Main()
        {
    
            int i = 2;
            int _j = (int)&i;
            int k = (int)(AddressType)_j;
            int* j = &k; 
    
            int l = *j;
            var s = (int*) l;
            int m = *s; 
    
            Console.WriteLine(m);
    
            var r = AddressType.b;
            AddressType* x = &r;
            AddressType y = *x;
    
            Console.WriteLine(y);
    
        }