Sunday, July 29, 2007

Trampolines

Developing embedded languages for applications in the past, the most time consuming part always seemed to be wrapping the multitude of foreign language (ie, to/from C++) function calls of interest with script-compatible functions.

One of the goals of Pair is to make working with other languages - especially C/C++ - very easy. So here we'll take a different approach. This time we'll generate trampolines to call foreign functions (for example, from a DLL) and do the boxing/unboxing of values for Pair to use. Trampolining has a number of different meanings but many of them center around the idea of generating code at runtime to call a function with special requirements that aren't known until runtime. In this case, we're directly generating the machine code necessary to set up the stack frame and call a function using either the __cdecl (for the C runtime library) or __stdcall (for the Win32 SDK functions) calling conventions.

This allows us to do things like the following -
(let
((beep
(import "kernel32.dll" stdcall uint Beep (uint uint)))
(system
(import "msvcrt.dll" cdecl uint system (string))))
(system "dir c:\\root")
(beep 500 1000))
C++ code -

nativecaller.h
nativecaller.cpp

1 comment: