winapiforthgforth

Is it possible to call the Windows API from Forth?


In C/C++, Windows executables are linked against static libraries that import DLL files containing Windows API procedures.

But how do we access those procedures from Forth code (e.g. GForth)? Is it possible at all?

I'm aware that there's Win32Forth capable of doing Win32 stuff, but I'm interested how (and if) this could be done in Forth implementations that lack this functionality from the box (yet do run on target OS and are potentially able to interact with it on a certain level).

What currently comes up to my mind is loading the DLL files in question and somehow locating the address of a procedure to execute - but then, execute how? (All I know is that Windows API uses the stdcall convention). And how do we locate a procedure without a C header? (I'm very new to Forth and just a bit less new to C++. Please bear with me if my musings are nonsense).


Solution

  • Yes, you could do this in Gforth according to its documentation. The biggest problem will be dealing with call backs, which the Windows API relies on rather heavily. There is an unsupported package to deal with this, see 5.25.6 Callbacks. I have not attempted this myself in Gforth, but the documentation looks adequate.

    You might also want to check MPE's VFXForth. From their website:

    Windows API Access

    VFX Forth can access all the standard Windows API calls, as well as functions in any other DLLs. The function interface allows API calls to be defined by cut and paste from other language reference manuals, for example:

    EXTERN: int PASCAL CreateDialogIndirectParam( HINSTANCE, void *,HWND, WNDPROC, LPARAM );
    EXTERN: int PASCAL SetWindowText( HANDLE, LPSTR );
    EXTERN: HANDLE PASCAL GetDlgItem( HANDLE, int );
    

    This is down the page a bit at VFX Forth for Windows.

    As I do my Forth on Mac and Linux, I can't work through the Windows for Gforth to provide more detail, sorry.