C is probably the only language you can do this in (except maybe Forth). Other languages either have no way of doing this, or don't treat data and code differently.
(Feel free to add examples for other languages here.)

Once you've got a pointer to your machine code (usually an array of bytes or ints), you need to cast it to the appropriate type and call it. Eg if you have a pointer to a function which takes a char *, you can call it like this

((int (*)(char *)) p)("hello, world");

The secret here is the parenthesis around the star. To declare a variable to hold the above, use this

int (*func_t)(char *);

In C (and C++), a function name is really just a pointer to a function, and you can think of () as an operator to make a call to that function. Using a typedef to hold the function type might make that clear

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, there is a function 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.

A library back-end may provide functionality that should behave differently for different front ends. For example, a library that wants to print out diagnostic messages uses a function pointer, and then a console app can pass a pointer to a function that prints out to the terminal (or stdout(3) or stderr(3)) while a graphical app can create a callback function that pops up a GUI window or something.

Some functions take another function as an argument. Probably the most well-known example is qsort(3) the quick sort algorithm -- you need to pass it an array and a function for comparing array elements. Also see the example below.

The trick is to cast the pointer to a function pointer of the required type

atexit( (void(*)())endwin );

It is worth noticing that in languages where functions are first class objects (such as LISP and Scheme), passing around pointers to functions is entirely normal (and type safe); even in Java and PythonIntrospection allows type safe access to such functionality.

Please note that any user can change the contents of pages on this site,
and therefore the Waikato Linux Users Group can offer no assurances that
the information is correct, and the information on this site is not
necessarily the opinion of the Waikato Linux Users Group, or any of its
members. If you have any complaints about the contents of this page,
please do not hesitate to contact the Waikato Linux Users Group, or, click
the Edit button!

Unless otherwise noted, all pages on this site are licensed under the
WlugWikiLicense.