【问题标题】:(C#) Convert int type to address type [closed](C#)将 int 类型转换为地址类型 [关闭]
【发布时间】:2018-01-31 07:04:55
【问题描述】:

我可以编译这样的代码

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

【问题讨论】:

  • 你想做什么需要不安全的代码?
  • 我希望 app1 和 app2 可以访问同一个内存位置,而不是访问同一个文件(太慢),只是为了好玩和好奇。
  • @DaveG 你不能只用指针来做到这一点。这就是memory-mapped files 的用途。
  • 如果可能的话,试着对地球上的每个病毒扫描程序都会对这样的操作感到恐惧......
  • 针对完全没有杀毒软件和互联网的半导体设备,我正在尝试写一个可以追踪每一个源代码行的应用程序。

标签: c# pointers unsafe


【解决方案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);

    }

【讨论】:

  • 那么我怎样才能从中得到“2”呢? *j 仍然是一个地址
  • 我已经提出了两种不同的方法来实现你想要的。在上面的代码中 int m 会取回你的'2',但在第二种方法中,我只是做枚举指针并将其取回。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-20
  • 1970-01-01
  • 2016-08-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多