Creating Function Pointers in C
Given the following functions, declare function pointers that point to them and include a sample call to each
Convert Java instance-method call into equivalent C code that uses function pointers
void pong(int i) {
printf(“pong: %d\n”, i); }
void (*a_param_func) (int); a_param_func = pong; a_param_func (3);
int pong_ret(int i) { printf(“pong: %d\n”, i); i++;
return i;
}
int (*a_param_ret_func) (int); a_param_ret_func = pong_ret; int x = a_param_ret_func (3); printf(“Return value: %d\n”, x);
Polymorphism Java
Java implements polymorphism through method overriding
Java waits until runtime to determine which object is being
referenced and then based on the reference it calls the associated method for that class. This is otherwise known as dynamic binding
C
C does not explicitly implement polymorphism
Polymorphism is achieved through the use of structs and
jump tables
Two structs are needed
o Jumptablestruct–holdsfunctionpointersforthe methods of the class
o Class struct – holds a reference to the class’s jumptable and stores any instance variables.
From C to Assembly with Function Pointers
Other Uses of function pointers
Difference between indirect jump and double-indirect jump
Indirect jump – set the pc to the address stored in rx
Double indirect jump – set the pc to the address that is stored
in the memory location in rx
Implement the calls to either proc or foo in assembly for the code snippets below
What prints to the screen Assume the following
The address of a[0] is 0x2000 The value of pachar 0x3000 The address of pofdt is 0x4000
0x2000 3
8 0x3000 0x3000 Mike m 0x3001 i
Write a function that creates a generic comparator function. The function should return 0 is the values are the same, -1 if the first is smaller, and 1 if the second is smaller. Feel free to test the function with the cmpStrings and cmpIntegers procedures in Module 1F
gpc $6, r6
j foo
gpc $2, r6
j *4(r5)
gpc $2, r6
j *16(r5)