Page 1 of 1
Returning Variables On Stack
Posted: Sun Dec 04, 2011 12:43 am
by Nessphoro
Hey guys,
I know that a function can return a stuct/class on a stack, but how would one do that in assembly?
I know the memory location is passed in EAX, but never actually figured out how to properly set up the stack.
With best regards
Re: Returning Variables On Stack
Posted: Sun Dec 04, 2011 1:52 am
by gerryg400
The struct isn't necessarily returned on the stack. The calling function supplies the address of a block of memory that will hold the structure. This is usually done in either a standard register or as a hidden parameter on the stack. The called function fills in the memory and returns the pointer back to the caller in the standard way.
The only tricky part is that the pointer must not point to a part of memory that the called function can access in another way. This means that if the returned value will be assigned to a global variable, the address of a temporary local variable is passed by the caller and the assignment to the global is done after the called function returns. Sometimes for large structs this will require a memcpy. If the returned value is being assigned to a local variable most compilers will pass the address of the local variable directly to the callee.