函数指针数组的汇编等价物?
Assembly equivalent of array of function pointers?
在 C 中,如果我想根据键盘输入调用一个函数,我会这样写:
#include <stdio.h>
char A(void) {
return 'a';
}
char B(void) {
return 'b';
}
char C(void) {
return 'c';
}
char (*CHARS[])(void) = {A, B, C};
int main(void) {
char calls[] = {'a', 'b', 'c'};
char c = CHARS[getc(stdin) - 'a']();
printf("%c\n", c);
return 0;
}
我可以在汇编中调用数组吗?如果该事实相关,我正在使用 nasm
编译内核。
编辑
刚才又玩了一些,我想出了:
jmp main
f0:
f1:
f2:
mov ax, 0
main:
mov bx, fns
add bx, ax
cmp bx, 0
je end
call [bx]
inc ax
jmp main
fns dw f0, f1, f2, 0
end:
hlt
以上是否正确(我实际上已经组装了两天)?
您可以创建一个跳转table,并修改PC(程序计数器)以跳转到table中的正确索引。例如
ADD PC, $c # Add index entered by the user to the PC
BRA function_a
BRA function_b
BRA function_c
end_jump_table:
# ...
还有其他地方:
function_a:
# do your thing
BRA end_jump_table
function_b:
# do your thing
BRA end_jump_table
function_c:
# do your thing
BRA end_jump_table
不是任何特定的汇编语言,但你明白了。
在 C 中,如果我想根据键盘输入调用一个函数,我会这样写:
#include <stdio.h>
char A(void) {
return 'a';
}
char B(void) {
return 'b';
}
char C(void) {
return 'c';
}
char (*CHARS[])(void) = {A, B, C};
int main(void) {
char calls[] = {'a', 'b', 'c'};
char c = CHARS[getc(stdin) - 'a']();
printf("%c\n", c);
return 0;
}
我可以在汇编中调用数组吗?如果该事实相关,我正在使用 nasm
编译内核。
编辑 刚才又玩了一些,我想出了:
jmp main
f0:
f1:
f2:
mov ax, 0
main:
mov bx, fns
add bx, ax
cmp bx, 0
je end
call [bx]
inc ax
jmp main
fns dw f0, f1, f2, 0
end:
hlt
以上是否正确(我实际上已经组装了两天)?
您可以创建一个跳转table,并修改PC(程序计数器)以跳转到table中的正确索引。例如
ADD PC, $c # Add index entered by the user to the PC
BRA function_a
BRA function_b
BRA function_c
end_jump_table:
# ...
还有其他地方:
function_a:
# do your thing
BRA end_jump_table
function_b:
# do your thing
BRA end_jump_table
function_c:
# do your thing
BRA end_jump_table
不是任何特定的汇编语言,但你明白了。