stos1512
stos1512

Reputation: 13

passing an array of chars to external assembly function

so my question is basic but i had a hard time finding anything on the internet. lets say i want to write a function in C that calls an external nasm function written in x86_64 assembly.

I want to pass to the external function two char* of numbers, preform some arithmetic operations on the two and return char* of the result. My idea was to iterate over [rdi] and [rsi] somehow and saving the result in rax (i.e add rax, [rdi], [rsi]) but I'm having a hard time to actually do so. what would be the right way to go over each character? increasing [rsi] and [rdi]? and also- I would only need to move to rax the value of the first character right?

Thanks in advance!

Upvotes: 0

Views: 757

Answers (1)

Samuel
Samuel

Reputation: 23

If you could post assembly/C code - it would be easier to suggest changes.

For any assembly, I would start with a C code(since I think in C :)) and then convert to assembly using a compiler and then optimize it in the assembly as needed. Assuming you need write a function which takes two strings and adds them and returns the result as int like the following:

int ext_asm_func(unsigned char *arg1, unsigned char *arg2, int len)
{
    int i, result = 0;
    for(i=0; i<len; i++) {
        result += arg1[i] + arg2[i];
    }
    return result;
}

Here is assembly (generated by gcc https://godbolt.org/g/1N6vBT):

ext_asm_func(unsigned char*, unsigned char*, int):
        test    edx, edx
        jle     .L4
        lea     r9d, [rdx-1]
        xor     eax, eax
        xor     edx, edx
        add     r9, 1
.L3:
        movzx   ecx, BYTE PTR [rdi+rdx]
        movzx   r8d, BYTE PTR [rsi+rdx]
        add     rdx, 1
        add     ecx, r8d
        add     eax, ecx
        cmp     r9, rdx
        jne     .L3
        rep ret
.L4:
        xor     eax, eax
        ret

Upvotes: 1

Related Questions