gpt4 book ai didi

c# - 不安全的指针操作

转载 作者:行者123 更新时间:2023-11-30 17:06:47 30 4
gpt4 key购买 nike

我正在尝试用 C# 编写一个 CPU 模拟器。机器的对象看起来像这样:

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
}

当我执行一条指令时,我有一个 switch 语句来决定指令的结果将存储在什么地方(寄存器或 RAM 的一个字)

我希望能够做到这一点:

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];
}

然后,当我执行指令后,我可以像这样简单地存储结果:

*resultContainer = result;

我一直在努力弄清楚如何在不扰乱 C# 的情况下做到这一点。

我如何使用 unsafe{}fixed(){ } 以及我可能不知道的其他东西来完成此操作?

最佳答案

这就是我的实现方式:

class Machine
{
short a, b, c, d;
short[] ram = new short[0x10000];

enum AddressType
{
Register,
DirectMemory,
}

// Gives the address for an operand or for the result.
// `addressType`and `addrCode` are extracted from instruction opcode
// `regPointers` and `ramPointer` are fixed pointers to registers and RAM.
private unsafe short* GetAddress(AddressType addressType, short addrCode, short*[] regPointers, short* ramPointer)
{
switch (addressType)
{
case AddressType.Register:
return regPointers[addrCode]; //just an example implementation
case AddressType.DirectMemory:
return ramPointer + addrCode; //just an example implementation
default:
return null;
}
}

public unsafe void tick()
{
fixed (short* ap = &a, bp = &b, cp = &c, dp = &d, ramPointer = ram)
{
short*[] regPointers = new short*[] { ap, bp, cp, dp };

short* pOperand1, pOperand2, pResult;
AddressType operand1AddrType, operand2AddrType, resultAddrType;
short operand1AddrCode, operand2AddrCode, resultAddrCode;

// ... decipher the instruction and extract the address types and codes

pOperand1 = GetAddress(operand1AddrType, operand1AddrCode, regPointers, ramPointer);
pOperand2 = GetAddress(operand2AddrType, operand2AddrCode, regPointers, ramPointer);
pResult = GetAddress(resultAddrType, resultAddrCode, regPointers, ramPointer);

// execute the instruction, using `*pOperand1` and `*pOperand2`, storing the result in `*pResult`.

}
}
}

要获取寄存器和 RAM 数组的地址,您必须使用 fixed 语句。此外,您只能在 fixed block 中使用获取的指针。所以你必须传递指针。

关于c# - 不安全的指针操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15183480/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com