你所看到的有一个type punning的例子。
void print_hello()
{
printf("hello");
}
int main()
{
void (*hello_func_ptr)() = &print_hello;
//we convert what the function points to to a string of "byte code"
char *func_byte_code = (char *)hello_func_ptr;
// prints out byte code of the function
printf(func_byte_code);
// we cast the string byte code to a function pointer
void (*func_from_byte_code)() = (void (*)())func_byte_code;
// we call the function we got from casting the byte code to a function pointer
(*func_from_byte_code)(); // prints "hello"!
return 0;
}
你的函数做的是取字节码字符串并将它转换回函数指针,就像我们上面所做的那样。然后可以通过解引用指针并通过添加括号和函数所需的任何参数来调用该函数来调用该函数。
当然,现在你不需要在常规编程中做这样的事情,但很少遇到特殊情况。
这是一个非常好的例子,你可能不应该这样做....函数指针转换是_almost_总是UB。 –
它将'code []'数组的第一个元素的地址赋给函数指针func –
这是编译吗? –