【发布时间】:2015-11-17 21:08:13
【问题描述】:
我想在 c 程序中使用 __asm 关键字了解 Visual Studio 上的汇编语言。
我尝试做的是; - 创建一个包含 5 个元素的 int 数组 - 遍历数组并将值添加到累加器
这是一个运行良好的代码;
#include <stdio.h>
int main()
{
int intArr[5] = { 1, 2, 3, 4, 5 };
int sum;
char printFormat[] = "Sum=%i\n";
__asm
{
lea esi, [intArr] // get the address of the intArr
mov ebx,5 // EBX is our loop counter, set to 5
mov eax, 0 // EAX is where we add up the values
label1: add eax, [esi] // add the current number on the array to EAX
add esi, 4 // increment pointer by 4 to next number in array
dec ebx // decrement the loop counter
jnz label1 // jump back to label1 if ebx is non-zero
mov[sum],eax // save the accumulated valu in memory
}
printf(printFormat, sum);
return 0;
}
输出如下;
Sum=15
我想将内联汇编部分用作一个单独的函数,并使用下面的函数调用做同样的事情;
#include <stdio.h>
// function declaration
int addIntArray(int[], int);
int main()
{
int intArr[5] = { 1, 2, 3, 4, 5 };
char printFormat[] = "Sum=%i\n";
int result;
result = addIntArray(intArr, 5);
printf(printFormat, result);
return 0;
}
int addIntArray(int intArr[], int size)
{
int sum;
__asm
{
lea esi, [intArr] // get the address of the intArr
mov ebx, 5 // EBX is our loop counter, set to 5
mov eax, 0 // EAX is where we add up the values
label1: add eax, [esi] // add the current number on the array to EAX
add esi, 4 // increment pointer by 4 to next number in array
dec ebx // decrement the loop counter
jnz label1 // jump back to label1 if ebx is non-zero
mov[sum], eax // save the accumulated value in memory
}
return sum;
}
输出很奇怪,如下所示;
Sum=2145099747
在调试时,我发现我只是将 esi 寄存器中存储的 地址值 相加,而不是 这些地址的内容。
我很困惑,为什么相同的内联汇编例程在我在主线程上运行时可以正常工作,而在我尝试在单独的函数上调用它时为什么不能正常工作。
问题出在哪里,为什么进程在 main 和 function 上的行为不同,我该如何解决?
【问题讨论】:
标签: arrays visual-studio pointers assembly x86