简体   繁体   English

在 C++ 中将 integer 传递给 x86 ASM

[英]Passing integer to x86 ASM in C++

I am trying to do some script hooking in C++, and have setup a simple test function for this case.我正在尝试在 C++ 中进行一些脚本挂钩,并为此案例设置了一个简单的测试 function。

   void __declspec(naked) testFunct()
{
    int myInt;
    myInt = 2000;
    __asm{
        mov eax, myInt
        jmp [jmp_back_address]
    }
}

when using this to pass in the integer, the function fails when it is called and the project crashes.当使用它传入 integer 时,function 在被调用时失败并且项目崩溃。 However, when using this instead, without an integer value, it successfully passes through.但是,当改用它时,没有 integer 值,它成功通过。

   void __declspec(naked) testFunct()
{
    __asm{
        mov eax, 2000
        jmp [jmp_back_address]
    }
} 

How can I successfully pass the integer?怎样才能顺利通过integer?

The assembler doesn't know what "myInt" means.汇编器不知道“myInt”是什么意思。 Most compilers support inline assembly with the possibility to pass values.大多数编译器都支持内联汇编,并可以传递值。 For instance, with GCC, you may try to define a macro like例如,对于 GCC,您可以尝试定义一个宏

#define MY_ASM_MACRO(myInt) ({ asm volatile("mov eax,%0\n\t \
          jmp [jmp_back_address]" : : "r"(myInt) : ); })

And use it like并像使用它一样

void __declspec(naked) testFunct()
{
   int myInt;
   myInt = 2000;
   MY_ASM_MACRO(myInt)
}

The correct solution for my situation was to simply do everything within the ourFunct() through ASM instead, as mixing both C++ and ASM for passing variables was creating buggy assembly code.针对我的情况,正确的解决方案是通过 ASM 简单地在 ourFunct() 中执行所有操作,因为将 C++ 和 ASM 混合用于传递变量会产生错误的汇编代码。 Example with a function call that works:有效的 function 调用示例:

int CalculateTotalScore()
{
    return (int)*Game::current_speed_score;
}

DWORD jmpBackAddress;
void __declspec(naked) ourFunct()
{
    __asm{
        call CalculateTotalScore
        jmp [jmpBackAddress]
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM