简体   繁体   中英

Pushing strings to C++ from MASM

So i'm attempting to make the game of Tik Tak Toe in MASM 32 bit but I cannot figure out how to pass a string from MASM to C++ to output text to the console. Any help would be much appreciated.

C++

// main.cpp
using namespace std;
#include<iostream>
#include<string>

extern "C" void asmMain();
extern "C" void printString(string msg);

int main() {
    asmMain();
    return 0;
}

void printString(string msg)
{
    cout << msg << endl;
}

Masm

.386
.MODEL FLAT, stdcall
.STACK 4096

printString PROTO C
.DATA
sIntroMessage BYTE "Welcome To Tik Tak Toe!"

.CODE
asmMain PROC C
    mov ecx, sIntroMessage
    call printString
asmMain ENDP
END

I'm Assuming you're using Microsoft's C/C++ compiler and assembler and if I recall the default calling convention is cdecl not stdcall mentioned in the comments. The stdcall directive in your assembly file applies if someone were to call your function from C/C++. In your assembly code if your functions take arguments then you need to ret the number of arguments*4. Assuming printString is cdecl, you need to push the arguments onto the stack instead of moving it to ecx then restore the stack pointer after the call is made.

.386
.MODEL FLAT, stdcall
.STACK 4096

printString PROTO C
.DATA
sIntroMessage BYTE "Welcome To Tik Tak Toe!"

.CODE
asmMain PROC C
    lea ecx, sIntroMessage
    push ecx
    call printString
    add esp,4
asmMain ENDP
END

Also mentioned in the comments your printString function should instead take a char* argument rather than a string object. Unless you want to construct the string object yourself in your assembly file which is more work and tedious.

using namespace std;
#include<iostream>
#include<string>

extern "C" void asmMain();
extern "C" void printString(char* msg);

int main() {
    asmMain();
    return 0;
}

void printString(char* msg)
{
    cout << msg << endl;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM