Returning Variables On Stack

Question about which tools to use, bugs, the best way to implement a function, etc should go here. Don't forget to see if your question is answered in the wiki first! When in doubt post here.
Post Reply
User avatar
Nessphoro
Member
Member
Posts: 308
Joined: Sat Apr 30, 2011 12:50 am

Returning Variables On Stack

Post 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
gerryg400
Member
Member
Posts: 1801
Joined: Thu Mar 25, 2010 11:26 pm
Location: Melbourne, Australia

Re: Returning Variables On Stack

Post 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.
If a trainstation is where trains stop, what is a workstation ?
Post Reply