Writing a C-wrapper for an ASM function

C-wrappers can be written for ASM functions in order to bring assembly speed and efficiency to small c. There are only two things involved in creating these wrappers:
  1. reading the parameters off the stack and into the proper registers
  2. returning a value.

Reading parameters off the stack

The parameters are placed on the stack from left to right, each taking up 2 bytes. So, in order to take a parameter off the stack, we must first compute its memory address.

If the parameter is an int or a pointer:
func(param1, param2) int param1, param2; {
#asm
   ld  hl,2          ; 2 is the offset of the last parameter
   add hl,sp         ; Add the stack pointer to hl.
   call LD_HL_MHL    ; Load param2 into hl
   ld  de,hl         ; Store param2 in de

   ld  hl,4          ; 4 is the offset of the second-to-last parameter
                     ; (in this case, the first parameter)
   add hl,sp
   call LD_HL_MHL    ; now param1 is in hl

   ...
   ; asm routine goes here
   ...
#endasm
}
If the parameter is a char:
func2(ch) char ch; {
#asm
   ld  hl,2          
   add hl,sp
   ld  b,(hl)        ; This is the location of the character
...

Returning a value

This is the easy part. The return value goes in hl. The only trick is that if you want to return an 8-bit value, the value goes in l, and h must be 0.

For example, to return the value currently stored in b:
   ...
   ; asm code
   ...
   ld  l,b           ; return value goes in l
   xor a             ; xor a is makes a = 0
   ld  h,a           ; h is now 0. Congrats!
#endasm
}
That's all!