Next: , Previous: Declaring C Functions, Up: C Interface


5.25.3 Calling C function pointers from Forth

If you come across a C function pointer (e.g., in some C-constructed structure) and want to call it from your Forth program, you can also use the features explained until now to achieve that, as follows:

Let us assume that there is a C function pointer type func1 defined in some header file func1.h, and you know that these functions take one integer argument and return an integer result; and you want to call functions through such pointers. Just define

     \c #include <func1.h>
     \c #define call_func1(par1,fptr) ((func1)fptr)(par1)
     c-function call-func1 call_func1 n func -- n

and then you can call a function pointed to by, say func1a as follows:

     -5 func1a call-func1 .

In the C part, call_func is defined as a macro to avoid having to declare the exact parameter and return types, so the C compiler knows them from the declaration of func1.

The Forth word call-func1 is similar to execute, except that it takes a C func1 pointer instead of a Forth execution token, and it is specific to func1 pointers. For each type of function pointer you want to call from Forth, you have to define a separate calling word.