简体   繁体   中英

C++ and Assembly Code (NASM) calling eachother

I am trying to compile assembly code that calls c++ function. And c++ code that calls assembly code. I am using Dev-C++4.9.9.2 and nasm in Windows 7. Can some show me how to compile the following codes so that they produce working programs. These codes are taken from lecture handouts.

Calling C++ from Assembly Example

//C++ file
#include <iostream>
using std::cout;

void swap(int *p1, int *p2);
{
    int temp = *p1;
    *p1 = *p2;
    *p2 = temp;
}

;NASM file    
extern _swap
x: dd 4
y: dd 7

push dword y
push dword x
call _swap
add esp, 8

Calling Assembly from C++ Example

;NASM file
global _swap
_swap:
    mov ecx, [esp+4]
    mov edx, [esp+8]
    mov eax, [ecx]
    xchg [ecx],eax
    ret


//C++ file
#include <iostream>
using std::cout;

void swap(int *p1, int *p2);

int main()
{
    int a = 10, b = 20;
    cout << "a=" << a << "b=" << b;
    swap(&a, &b);
    cout << "a=" << a << "b=" << b;
    system("PAUSE");
    return 0;   
}

Also it will be very helpful if some one can show me how to program the same code using Visual Studio 2010 C++ and NASM.

Symbols in C++ undergo name mangling . To make simple functions directly linkable with foreign code, you need to declare them (at least) as extern "C" :

extern "C" void swap(int *, int *)

You also need to make sure that the calling conventions match. (For example, I believe that fastcall on x86_64 passes integral arguments in registers, not on the stack.)

A "foreign function interface" (ffi) library can help make this sort of cross-language interoperation easier.

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