User`s manual

Dynamic C Users Manual digi.com 185
11.6 Assembly Calling C
A program may call a C function from assembly code. To make this happen, set up part of the stack frame
prior to the call and “unwind” the stack after the call. The procedure to set up the stack frame is described
here.
1. Save all registers that the calling function wants to preserve. A called C function may change the value
of any register. (Pushing registers values on the stack is a good way to save their values.)
2. If the function return is a struct, reserve space on the stack for the returned structure. Most functions
do not return structures.
3. Compute and push the last argument, if any.
4. Compute and push the second to last argument, if any.
5. Continue to push arguments, if there are more.
6. Compute and push the first argument, if any. Also load the first argument into the primary register (HL
for int, unsigned int, char, and pointers, or BCDE for long, unsigned long, and
float) if it is of a primitive type.
7. Issue the call instruction.
The caller must unwind the stack after the function returns.
1. Recover the stack storage allocated to arguments. With no more than 6 bytes of arguments, the program
may pop data (2 bytes at time) from the stack. Otherwise, it is more efficient to compute a new SP
instead. The following code demonstrates how to unwind arguments totaling 36 bytes of stack storage.
2. If the function returns a struct, unload the returned structure.
3. Restore registers previously saved. Pop them off if they were stored on the stack.
4. If the function return was not a struct, obtain the returned value from HL or BCDE.
; Note that HL is changed by this code!
; Use “ex de,hl” to save HL if HL has the return value
;;;ex de,hl ; save HL (if required)
ld hl,36 ; want to pop 36 bytes
add hl,sp ; compute new SP value
ld sp,hl ; put value back to SP
;;;ex de,hl ; restore HL (if required)