首页 > 解决方案 > 如何在汇编中调用函数?

问题描述

我将如何将我的汇编代码的一部分指定为函数并从 _asm {} 块中调用该函数?例如,我希望函数从 for 循环开始,“n”个元素填充了一个值。

#include <stdio.h>
#include <string.h>


void printBytes(char *data, int length)
{
    int x;
    for (x = 0; x < length; x++)
    {
        if ((x & 0xF) == 0) printf("\n");
        printf("%02X ", (unsigned char)data[x]);
    }
    printf("\n\n");
    return;
} // printBytes

void function(){

    char string[] = "The end is near!";
    void* dst = &string;
    unsigned char value = 0xA5;
    int nCount = 5;

    printf("The message is: %s\n", string);
    printBytes(string, strlen(string)); 

    __asm {

        //type cast the str from void* to char*
            mov eax, DWORD PTR [dst]
            mov DWORD PTR [ebp-88], eax

        //fill "n" elements/blocks with value
            mov DWORD PTR [ebp-76], 0
            jmp label_3
        label_2:
            mov eax, DWORD PTR[ebp-76]
            add eax, 1
            mov DWORD PTR [ebp-76], eax
        label_3:
            mov eax, DWORD PTR [ebp-76]
            cmp eax, DWORD PTR [nCount]
            jge EXIT

            mov eax, DWORD PTR [ebp-88]
            add eax, DWORD PTR [ebp-76]
            mov cl, BYTE PTR [value]
            mov BYTE PTR[eax], cl
            jmp label_2
        EXIT:

    }// asm_memset */

    printf("Now the message is: %s\n", string);
    printBytes(string, strlen(string));
    return;

}

int main() {

    function();

    printf("Press ENTER key to continue...");
    getchar();
    return(0);
}

标签: cassemblyvisual-c++x86inline-assembly

解决方案


请注意,您的问题的解决方案可能是不可移植的。

您需要为您的架构/系统/编译器找到ABI,并遵守其调用约定。


推荐阅读