views:

1288

answers:

3

How do you call a client codes methods from inside a class defined in the client code?

For example, I have a memory reading class, that can read values from the memory of a process at a certain address. I also have classes for managing the type of data that is read from memory (I am reading about an in-game 'object'. In the 'client code' I am calculating the 'base address' of that object in memory, then initializing my 'object class' using a constructor that takes the 'base address' as a parameter. This base class should then be able to tell me things about that object through methods because the objects know how far away from the base address a certain value is, such as 'health')

I tried using code such as this, and it gave me an error. 'ObjectManager' is the class which can read values from memory.

class ObjectManager : Memory
{
    LocalCharacter LocalPlayer = new LocalCharacter(this);
    // other things omitted
}
// Error: Keyword 'this' is not available in the current context

and this, out of desperation:

class ObjectManager : Memory
{
    LocalCharacter LocalPlayer = new LocalCharacter(ObjectManager);
    // other things omitted
}
// Error: Keyword 'this' is not available in the current context

But to no avail. What is the best way to do this?

+10  A: 

How about referencing 'this' in the constructor:-

class ObjectManager : Memory
{
    ObjectManager()
    {
        LocalPlayer = new LocalCharacter(this);
    }

    LocalCharacter LocalPlayer;
    // other things omitted
}
kronoz
A: 

because you are not in a method.

You must declare a method to access this. Your main function would invoke the call.

If you wish to set a class level field then you will need to do it in the constructor. You still declare the variable in your class definition though (not in a method)

class ObjectManager : Memory
{
   public void mymethod()
   {
      LocalCharacter LocalPlayer = new LocalCharacter(this);
   }
}
Spence
A: 

Thankyou very much. It worked!

This isn't an answer, please keep thanks etc in the comments - welcome to Stack Overflow James!
Sam Meldrum
Which answer helped? Please accept (tick) the answer that sorted your problem out!
kronoz