Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unsafe pointer manipulation

I'm trying to write a CPU emulator in C#. The machine's object looks like this:

class Machine 
{
    short a,b,c,d; //these are registers.

    short[] ram=new short[0x10000];  //RAM organised as 65536 16-bit words

    public void tick() { ... } //one instruction is processed
}

When I execute an instruction, I have a switch statement which decides what the result of the instruction will be stored in (either a register or a word of RAM)

I want to be able to do this:

short* resultContainer;

if (destination == register)
{
    switch (resultSymbol) //this is really an opcode, made a char for clarity
    {
       case 'a': resultContainer=&a;
       case 'b': resultContainer=&b;
       //etc
    }
}
else
{
    //must be a place in RAM
    resultContainer = &RAM[location];
}

then, when I've performed the instruction, I can simply store the result like:

*resultContainer = result;

I've been trying to figure out how to do this without upsetting C#.

How do I accomplish this using unsafe{} and fixed(){ } and perhaps other things I'm not aware of?

like image 734
Matthew Sainsbury Avatar asked Apr 23 '26 00:04

Matthew Sainsbury


1 Answers

What if we look at the problem from another view? Execute the instruction and store the result in a variable (result), and then decide on where you should put the result. Doesn't work?

like image 87
Mohammad Dehghan Avatar answered Apr 25 '26 15:04

Mohammad Dehghan