6.28.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 could use the structures as described above by defining a macro. Or you use c-funptr.

c-funptr ( "forth-name" <{>"c-typecast"<}> "{type}" "—" "type" –  ) gforth-1.0 “c-funptr”

Define a Forth word forth-name. Forth-name has the specified stack effect plus the called pointer on top of stack, i.e. ( {type} ptr -- type ) and calls the C function pointer ptr using the typecast or struct access c-typecast.

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-funptr call-func1 {((func1)ptr)} n -- n

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

-5 func1a call-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.