5
            ...
            {
                int *r1, *r2;
                r1 = GetCorrectRegister(first);
                r2 = GetCorrectRegister(second);
                switch ((OpCode)current.opcode)
                {
                    case OpCode.ADDR:
                        r2 = r1 + r2;
                        break;
                }
            }
            ...

This is the obvious, easiest way to solve this problem. However, I'd prefer not to use an unsafe method if I can avoid it. Basically, I have a bunch of integers which represent registers. There are assembly instructions that take register mnemonics as arguments. I'd prefer not to have the logic to determine which variable to assign to in each branch of the switch statement or make some sort of kludgey GetRegisterValue(mnemonic) and SetRegisterValue(mnemonic) functions. Is there some C#y way to do something similar?

3
  • use Delegates in C# it can act as functional pointers Commented Feb 13, 2011 at 7:18
  • 2
    r2=r1+r2 ? You meant *r2=*r1+*r2, didn't you? Commented Feb 13, 2011 at 7:42
  • Yes, I meant *r2=*r1+*r2, sorry. Commented Feb 13, 2011 at 16:51

2 Answers 2

5

I have a bunch of integers which represent registers

The obvious thing here is not to have a bunch of integers. Create an array

 int[] registers = new int[NUMBER_OF_REGISTERS];

Your above code turns into

    {
            int r1Index, r2Index;
            r1Index = GetCorrectRegisterIndex(first);
            r2Index = GetCorrectRegisterIndex(second);
            switch ((OpCode)current.opcode)
            {
                case OpCode.ADDR:
                    registers[r1Index] = registers[r1Index] + registers[r2Index];
                    break;
            }


     }

Additionally, use an enum to create symbolic names for your register names where each name gives you the right index.

Sign up to request clarification or add additional context in comments.

2 Comments

If I wanted to index into an array using an enum value, I'd have to cast every time, right? registers[(int)Registers.A]?
@Paul: yes, that is true, read this SO post stackoverflow.com/questions/3091267/converting-enum-to-int for more information.
1

How about using a class and ref parameters?

class Registers
{
    public int EAX;
    public int EBX;
    //...

    public void ExecuteBinaryOperation(int opCode, ref int r1, ref int r2)
    {
        // ...
        // binary operation ADD.
        r2 = r1 + r2;
        //...
    }
}

and in code:

registers.ExecuteBinaryOperation(0, ref registers.EAX, ref registers.EBX);

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.