简体   繁体   中英

Passing an array as argument to a x86 function from C

I have a bmp file and I read it in ac function and store the values of pixels as unsigned integer. I want to pass this unsigned integer array to x86 but I fail. Here is my c code:

I have this properties:

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

And my main method is :

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

I check my array and it has true values.

Here is my nasm code:

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   

I expect ecx to have first element of my array but instead of that I get 1455843040 And address probably?

And here is the 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;
}

My ultimate goal is to take the elements of the array (which is in the interval of 0 - 255) and increment corresponding value in my 255 byte sized array. For example if the first element is 55 in my first array, I will increment 55th element by one in the 255-byte-sized array. So I need access to the elements of the array that I pass from c.

When you have a C prototype extern int func(char *a); you are passing a pointer to the character array a on the stack. Your assembly code does this:

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

EBP+8 is a memory operand (on the stack) where the address of a was placed by the calling function. You ended up retrieving the pointer to a (1455843040) from the stack. What you need to do is further dereference the pointer to get individual elements. You could do so with code like:

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. 

To get the second byte in the array:

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

An so on.

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