[英]C++ and Assembly Code (NASM) calling eachother
I am trying to compile assembly code that calls c++ function. 我正在尝试编译调用c ++函数的汇编代码。 And c++ code that calls assembly code.
和调用汇编代码的c ++代码。 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.
我在Windows 7中使用Dev-C ++ 4.9.9.2和nasm。有些人可以告诉我如何编译以下代码,以便它们生成工作程序。 These codes are taken from lecture handouts.
这些代码来自讲义。
Calling C++ from Assembly Example 从Assembly Example调用C ++
//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 从C ++示例调用程序集
;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. 如果有人能告诉我如何使用Visual Studio 2010 C ++和NASM编写相同的代码,那将非常有用。
Symbols in C++ undergo name mangling . C ++中的符号经历了名称修改 。 To make simple functions directly linkable with foreign code, you need to declare them (at least) as
extern "C"
: 要使简单函数可以直接与外部代码链接,您需要将它们(至少)声明为
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.) (例如,我相信x86_64上的
fastcall
在寄存器中传递整数参数,而不是在堆栈上传递。)
A "foreign function interface" (ffi) library can help make this sort of cross-language interoperation easier. “外部函数接口”(ffi)库可以帮助简化这种跨语言的互操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.