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!!

2
  • 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. Commented May 23, 2015 at 19:04
  • 1
    i don't get the reason this is downvoted Commented Dec 13, 2016 at 3:51

2 Answers 2

9

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();
Sign up to request clarification or add additional context in comments.

1 Comment

Might also be worth noting that he'll have to tick Allow unsafe code for his project.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.