-1

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;
}
DaveG
  • 491
  • 1
  • 6
  • 19
  • 1
    What are you trying to do that requires unsafe code? – ProgrammingLlama Jan 31 '18 at 07:08
  • I want app1 and app2 can access the same memory location, not access the same file(too slow), just for fun and curious. – DaveG Jan 31 '18 at 07:16
  • 1
    @DaveG You're not going to be able to do that with just pointers. That's what [memory-mapped files](https://learn.microsoft.com/en-us/dotnet/standard/io/memory-mapped-files) are for. – Kyle Jan 31 '18 at 07:20
  • Try to be a little more curious about how much every virus scanner on earth would freak out over such an operation if it were possible... – Nyerguds Jan 31 '18 at 07:22
  • It is for semiconductor equipment that are totally free of anti-virus software and internet, I am try to write a application that can trace every source code line. – DaveG Jan 31 '18 at 07:26
  • In a 64-bit application, the address would be 64-bit as well, but `int` is only 32-bit. Additionally, you cannot access the memory of another application through pointers only, you need to use special functions to read and write memory in another process, or set up some shared memory. – Lasse V. Karlsen Jan 31 '18 at 08:02
  • @Kyle I take a look at memory-mapped files, so the address that app1 get won't be the same in app2 in real storage location, so it is impossible to achieve this goal I guess – DaveG Jan 31 '18 at 08:05
  • @Lasse Vågsæther Karlsen Thanks, I know that, but I need access the memory really fast or it will delay the equipment operation – DaveG Jan 31 '18 at 08:11

1 Answers1

1

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

    }
sbp
  • 913
  • 8
  • 19
  • So how can I get the '2' back from this? *j is still an address – DaveG Jan 31 '18 at 07:37
  • I've put two different approaches to achieve what you wanted. In above code int m would get back your '2' but in the second approach I'd just do enum pointer and retrieve it back. – sbp Jan 31 '18 at 08:28