Assembly equivalent of array of function pointers?

895 views Asked by At

In C, if I wanted to call a function based on keyboard input, I would write something like:

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

Can I make an array of calls in assembly? I am using nasm to compile a kernel if that fact has relevance.

EDIT Playing around some more just now, I came up with:

        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

Is the above correct (I'm literally like two days into assembly)?

1

There are 1 answers

0
Gauthier On BEST ANSWER

You can create a jump table, and modify the PC (program counter) to jump to the right index in the table. For example

    ADD PC, $c      # Add index entered by the user to the PC
    BRA function_a
    BRA function_b
    BRA function_c
end_jump_table:
    # ...

And somewhere else:

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

Not in any particular assembly language, but you get the idea.