2

I have a specific address (let's call it ADR) in my memory with a specific value (let's assume 4 bytes int)

I want to crate an int variable in c# and change the address to that variable to ADR so when I do for example; print myVar it prints the value stored in ADR.

I know I can make an IntPtr(ADR) and then use Marshal Methods to get the value but I want a way to do this without calling a method everytime I have to read the value.

Thanks!!

Lolrapa
  • 183
  • 1
  • 9
  • I think the address of local variables is always somewhere on the stack, and the address of a field in an object is some offset from the address of the object. So I don't know of a type of "variable" for which you would be able to choose the address. – adv12 May 23 '15 at 19:04
  • 1
    i don't get the reason this is downvoted – Ahmed Fwela Dec 13 '16 at 03:51

2 Answers2

8

Did you know you can use pointers in C#?

int someVariable = 0;

unsafe
{
    int* addr = &someVariable;
    *addr = 42;
}

Console.WriteLine(someVariable); // Will print 42

If you already have an address you can just write:

int* addr = (int*)0xDEADBEEF;

Or, from an IntPtr:

var intPtr = new IntPtr(0xDEADBEEF);
int* addr = (int*)intPtr.ToPointer();
Lucas Trzesniewski
  • 50,214
  • 11
  • 107
  • 158
  • 1
    Might also be worth noting that he'll have to tick `Allow unsafe code` for his project. – Chris May 23 '15 at 20:10
0

One directly approach is invoking ASM code in your C# code, as you can see in Invoking Assembly Code in C#. Another appropriate option is to use pointers.

Mihai8
  • 3,113
  • 1
  • 21
  • 31