-3

I am working on a memory reader/writer class, but i am stuck with it. My problem is that i want to modify an other process memory values with a struct pointer. I know how to do it in C++ but not with C#

My current code is:

class CModifier
{
    struct Data
    {
        int iMember;
        float fMember;
    }

    public CModifier()
    {
        Data data[62];
        *data = 0x123456;

        // use them to modify values etc.
        data.fMember = 1.2345f;
    }
}
Chris
  • 1
  • 5

2 Answers2

2

C# does allow limited access to memory locations, but it is not really recommended, and should only be attempted once you know how other systems such as garbage collection handle your memory. The reference operator & and the de-reference operator * are used for accessing memory. you also must use the unsafe keyword in your method declaration. as an example:

public unsafe void Method()
{
    int x = 10;
    int y = 20;
    int *ptr1 = &x;
    int *ptr2 = &y;
    Console.WriteLine((int)ptr1);
    Console.WriteLine((int)ptr2);
    Console.WriteLine(*ptr1);
    Console.WriteLine(*ptr2);
}

Note that there are other more advanced things to consider, such as Pinning memory locations to stop the garbage collector from moving the object in memory, and the effect this process would have on your stack heap.

Bottom line, Use pointer references at your own risk, and only as a last resort.

Claies
  • 22,124
  • 4
  • 53
  • 77
-2

I feel like C++ professionals are going to lambast my post for not using correct technical terms, but oh well.

C# has an 'unsafe' modifier you can use to have pointer-adjusting code, but a better option for modifying structs in another location is the 'ref' keyword.

I can't say -exactly- what you're trying to accomplish can be done in C# (heck, I'm not sure I'd understand it in C++), but here's how I'd do it, as you've described.

void ChangeMyStruct(ref Data etc) {
  data.fMember = 1.2345f;
}

void mainMethod() {
  ChangeMyStruct(ref dataOne);
}
Katana314
  • 8,429
  • 2
  • 28
  • 36
  • 1
    Prefacing your answer with the semantic equivalent of "I don't know what I am talking about, but here goes anyways." is a big red flag that you shouldn't be attempting to answer this question. – Pieter Geerkens Sep 07 '13 at 15:42
  • @PieterGeerkens I'm mainly saying that I don't know about C++, but I believe I know effective ways of solving his question is in the language he's asking about. – Katana314 Sep 07 '13 at 15:43
  • 1
    Like Horton the elephant: Say what you mean, and mean what you say. – Pieter Geerkens Sep 07 '13 at 15:44
  • @PieterGeerkens "I'm not sure I'd understand it in C++" - like that? Your criticisms are not helpful. – Katana314 Sep 07 '13 at 15:47