(C#)将int类型转换为地址类型

时间:2018-01-31 07:04:56

标签: c# pointers unsafe

我可以编译像这样的代码

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

但是如何将地址类型转换为int类型,反之亦然?像:

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

1 个答案:

答案 0 :(得分:1)

不知道你想要达到的目标;在得到指针之前,你必须将它强制转换为int。但这是一个指向指针地址的指针。

    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);

    }