I need to call PrintResult from my assembly to display the result. I know I have to use extrn _PrintResult somewhere, and I should call the function using call _PrintResult but
I usually don't like to post full code for things, but give this a try:
.386
.model flat
.code
_Square proc
mov eax, [esp+4]
imul eax
push eax ; Save the calculated result
; Call PrintResult here
push eax ; value
push 0 ; ShowSquare
call _PrintResult
add esp, 8 ; Clear the stack
pop eax ; Return the calculated result
ret
_Square endp
#include
using namespace std;
enum ResultCode {ShowSquare};
enum SuccessCode {Failure, Success};
extern "C" long Square(long);
int main(int argc, char* argv[])
{
long Num1, Num2;
do
{
cout << "Enter number to square" << endl;
cin >> Num1;
Num2 = Square(Num1);
cout << "Square returned: " << Num2 << endl;
}
while (Num2);
return 0;
}
extern "C"
void PrintResult(ResultCode result, long value)
{
switch (result)
{
case ShowSquare:
cout << "Square is: " << value << endl;
break;
default:
cout << "Error calculating square" << endl;
break;
}
}
Because you are writing a C program, the default calling mechanism is cdecl which means that all the parameters are passed on the stack, the return value is passed back in eax
, and the caller is responsible for cleaning up the stack afterward.
So in order to call PrintResult, you have to push all of your parameters onto the stack before invoking the procedure. And after the procedure returns, we have to clean up our stack (add esp, 8
).
Because the cdecl calling convention allows eax
to be modified during the call, eax
may not be preserved when PrintResult returns, so we save the calculated result before calling PrintResult and then restore it after the call returns.
I have not tried the above code, but I hope it helps get you going down the right track.
Note: Because you are using a C++ compiler, the extern "C"
before PrintResult is required.