gpt4 book ai didi

c - 将数组作为参数从 C 传递给 x86 函数

转载 作者:行者123 更新时间:2023-11-30 18:33:37 25 4
gpt4 key购买 nike

我有一个 bmp 文件,我在 c 函数中读取它并将像素值存储为无符号整数。我想将这个无符号整数数组传递给 x86 但失败了。这是我的 C 代码:

我有这个属性:

extern int func(char *a);
unsigned char* image;

我的主要方法是:

int main(void){
image = read_bmp("cur-03.bmp");
int result = func(image);
printf("\n%d\n", result);
return 0;
}

我检查了我的数组,它有真实值。

这是我的 nasm 代码:​​

section .text
global func

func:
push ebp
mov ebp, esp
mov ecx , DWORD [ebp+8] ;address of *a to eax


pop ebp
ret

section .data
values: TIMES 255 DB 0

我希望 ecx 具有数组的第一个元素,但我得到的不是 1455843040 可能还有地址?

这是 read_bmp:

unsigned char* read_bmp(char* filename)
{
int i;
FILE* f = fopen(filename, "rb");
unsigned char info[54];
fread(info, sizeof(unsigned char), 54, f); // read the 54-byte header

// extract image height and width from header
int width = *(int*)&info[18];
int height = *(int*)&info[22];
int heightSign =1;
if(height<0){
heightSign = -1;
}

int size = 3 * width * abs(height);
printf("size is %d\n",size );
unsigned char* data = malloc(size); // allocate 3 bytes per pixel
fread(data, sizeof(unsigned char), size, f); // read the rest of the data at once
fclose(f);

return data;
}

我的最终目标是获取数组的元素(在 0 - 255 的区间内)并在 255 字节大小的数组中增加相应的值。例如,如果第一个数组中的第一个元素是 55,我将在 255 字节大小的数组中将第 55 个元素递增 1。所以我需要访问从 c 传递的数组元素。

最佳答案

当你有一个C原型(prototype)extern int func(char *a);时,你正在传递一个指向字符数组a的指针堆栈。您的汇编代码执行以下操作:

push ebp
mov ebp, esp
mov ecx , DWORD [ebp+8] ;address of *a to eax

EBP+8 是一个内存操作数(在堆栈上),调用函数将 a 的地址放置在其中。您最终从堆栈中检索了指向 a (1455843040) 的指针。您需要做的是进一步取消引用指针以获取各个元素。您可以使用如下代码来做到这一点:

push ebp
mov ebp, esp
mov eax , DWORD [ebp+8] ; Get address of character array into EAX
mov cl, [eax] ; Get the first byte at that address in EAX.

获取数组中的第二个字节:

mov cl, [eax+1]         ; Get the second byte at that address in EAX.

等等。

关于c - 将数组作为参数从 C 传递给 x86 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56304487/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com