How do you call Win32 API functions from inline as

2019-07-09 12:28发布

问题:

Would somebody please tell me whats wrong with this code I am just calling a Sleep function from the kernel32.dll What's wrong? I am using Visual Studio 2008. Any help would be grateful. Thank you very much.

__asm
{
    mov eax, 77e2ef66h
    push 9999
    call eax
}

回答1:

Where did you get that magic number, 77e2ef66h? Usually if you're calling Win32 API functions from inline assembler, you'd do something like:

__asm 
{ 
    push 9999 
    call Sleep
} 

Functions in Win32 do not have a fixed address (regardless of what your "DLL Export Viewer" might show). Functions are linked by name or ordinal at load time (by the Windows PE loader) and are not located at fixed addresses. In fact, the actual address of functions can change between versions of Windows, subreleases within the same version of Windows, from machine to machine, and even possibly from one run of your program to the next.

(Disclaimer: It's been a very long time since I've done this, so the details of the above code example are undoubtedly wrong, but I know that you definitely don't need to use magic numbers.)