嘿,我想知道是否有人可以帮助我使用 C 语言的一流标签。
我目前正在尝试从内存(AVR设备的闪存)读取java字节码,我想将每条指令视为一个标签,并通过使用goto语句并跳转到适当的标签来分派(dispatch)指令。
但问题是我用来从内存读取指令的函数返回一个无符号字节。
u08_t nvmfile_read08(void *addr) {
u08_t val;
addr = NVMFILE_ADDR(addr); // remove marker (if present)
memcpy_P((u08_t*)&val, (PGM_P)addr, sizeof(val));
return val;
}
instr = nvmfile_read08(pc);
所以我的问题是如何将 instr 转换为类似的内容:
void *ptr;
ptr = &&instr;
goto *ptr;
理想情况下,此代码将跳转到此标签:(假设 iload 是最后读取的指令)
iload:
// Execute the iload jvm instruction.
谢谢
最佳答案
有两种方法:switch
语句或函数指针数组。
switch
的情况可以通过枚举器命名,如下所示:
enum jvm_opcodes {
push = 0,
pop = 1,
/* etc */
blah = 254
};
然后开关看起来像这样:
switch ( instr ) {
case push: {
} break;
case pop: {
} break;
}
函数指针数组将直接分派(dispatch)到其他函数,而无需编写开关
。如果源代码分布在更多文件中可能会更方便。
/* dispatch.c */
typedef void (*jvm_dispatch)(); /* function pointer type */
jvm_dispatch insn_dispatch_table[] = { /* define array */
handle_push, /* opcode 0 */
handle_pop, /* opcode 1 */
/* etc */
};
insn_dispatch_table[ insn ](); /* call an entry from the array */
/* push.c */
void handle_push() {
}
/* pop.c */
void handle_pop() {
}
关于c - C 中的第一类标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14303771/