Reducing size of switch statement in emulator?

梦想的初衷 提交于 2020-01-14 10:34:30

问题


I started writing a DCPU-16 emulator using this v1.7 spec. I started laying down the architecture, and I don't like the fact that I'm using very long switch statements. This is my first time writing an emulator, and so I don't know if there's better way to be doing it. While the switches aren't that large, due to the DCPU's small number of opcodes (and the fact that I haven't actually implemented the instructions yet), I can imagine if I were writing an emulator for a larger instruction set the switch statements would be huge.

Anywhom, here's my code.

EDIT: I forgot to get my question across:

  • Is there a better way to design an emulator than using a massive switch?

回答1:


This approach seems reasonable to me. It is certainly how I would do it (I have written a few CPU emulators and similar types of code).

The nearest alternative is a set of function pointers, but some of your cases will probably be rather simple (e.g. cpu_regs.flags &= ~CARRY or if (cpu_regs.flags & CARRY) do_rel_jump(next_byte());, so using function pointers will slow you down.

You can bunch all the "No Operation Specified yet" to one place, that will make it a lot shorter in number of lines, but the number of cases will of course still be the same [unless you put it in default:].



来源:https://stackoverflow.com/questions/17187712/reducing-size-of-switch-statement-in-emulator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!