簡體   English   中英

從C將數組作為參數傳遞給x86函數

[英]Passing an array as argument to a x86 function from C

我有一個bmp文件,並在ac函數中讀取該文件,並將像素值存儲為無符號整數。 我想將此無符號整數數組傳遞給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個元素增加一個。 因此,我需要訪問從c傳遞過來的數組元素。

當您有C原型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.

等等。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM