Penguin
Diff: CastingPointerToFunction
EditPageHistoryDiffInfoLikePages

Differences between version 5 and previous revision of CastingPointerToFunction.

Other diffs: Previous Major Revision, Previous Author, or view the Annotated Edit History

Newer page: version 5 Last edited on Wednesday, January 22, 2003 4:22:37 pm by JohnMcPherson Revert
Older page: version 4 Last edited on Monday, November 11, 2002 12:14:09 am by PerryLorier Revert
@@ -23,6 +23,27 @@
 ----- 
  
 And you need to do this why? 
  
-1. Jon was using it to "compile" something then jump to it in C, by casting an array as a function, then calling it.  
-2. I use it frequently to do things like have a lookup table of name to function. For example in ircu, theres a functino called "parse" which takes a line from a user, splits it up into a function and it's arguments, then scans through a table of functions and their names, when it finds one that matches that command, it calls the function with the arguments it parsed earlier. Nice 'n zippy. 
+* Jon was using it to "compile" something then jump to it in C, by casting an array as a function, then calling it.  
+  
+* I use it frequently to do things like have a lookup table of name to function. For example in ircu, theres a functino called "parse" which takes a line from a user, splits it up into a function and it's arguments, then scans through a table of functions and their names, when it finds one that matches that command, it calls the function with the arguments it parsed earlier. Nice 'n zippy.  
+  
+* Some functions take another function as an argument. See the example below.  
+  
+  
+from atexit(1):  
+ #include <stdlib.h>  
+ int atexit(void (*function)(void));  
+  
+you can specify functions to be executed after main() finishes.  
+You do this by calling atexit(functionname), as a function name  
+without () is a pointer to that function. However, if you want to this for a function that returns something other than null, you have to type cast it. Eg:  
+ (int endwin() is an ncurses function).  
+  
+ atexit(endwin);  
+ source.cpp:227: passing `int (*)()' as argument 1 of `atexit(void (*)())'  
+ atexit(void)endwin);  
+ source.cpp:227: void value not ignored as it ought to be  
+  
+The trick is to cast the pointer to a function pointer of the required type:  
+ atexit( (void(*)())endwin );