What is __stdcall?

2019-01-04 05:05发布

I'm learning about Win32 programming, and the WinMain prototype looks like:

int WINAPI WinMain ( HINSTANCE instance, HINSTANCE prev_instance, PSTR cmd_line, int cmd_show )

I was confused as to what this WINAPI identifier was for and found:

#define WINAPI      __stdcall

What does this do? I'm confused by this having something at all after a return type. What is __stdcall for? What does it mean when there is something between the return type and function name?

8条回答
Explosion°爆炸
2楼-- · 2019-01-04 05:42

The answers so far have covered the details, but if you don't intend to drop down to assembly, then all you have to know is that both the caller and the callee must use the same calling convention, otherwise you'll get bugs that are hard to find.

查看更多
Evening l夕情丶
3楼-- · 2019-01-04 05:43

__stdcall is used to put the function arguments in the stack. After the completion of the function it automatically deallocates the memory. This is used for fixed arguments.

void __stdcall fnname ( int, int* )
{
    ...
}

int main()
{
    CreateThread ( NULL, 0, fnname, int, int*...... )
}

Here the fnname has args it directly push into the stack.

查看更多
神经病院院长
4楼-- · 2019-01-04 05:50

I agree that all the answers so far are correct, but here is the reason. Microsoft's C and C++ compilers provide various calling conventions for (intended) speed of function calls within an application's C and C++ functions. In each case, the caller and callee must agree on which calling convention to use. Now, Windows itself provides functions (APIs), and those have already been compiled, so when you call them you must conform to them. Any calls to Windows APIs, and callbacks from Windows APIs, must use the __stdcall convention.

查看更多
手持菜刀,她持情操
5楼-- · 2019-01-04 05:50

It has to do with how the function is called- basically the order in which things are put on the the stack and who is responsible for cleanup.

Here's the documentation, but it doesn't mean much unless you understand the first part:
http://msdn.microsoft.com/en-us/library/zxk0tw93.aspx

查看更多
▲ chillily
6楼-- · 2019-01-04 05:50

I never had to use this before until today. Its because in my code I am using multi-threadding and the multi-threading API I am using is the windows one (_beginthreadex).

To start the thread:

_beginthreadex(NULL, 0, ExecuteCommand, currCommand, 0, 0);

The ExecuteCommand function MUST use the __stdcall keyword in the method signature in order for beginthreadex to call it:

unsigned int __stdcall Scene::ExecuteCommand(void* command)
{
    return system(static_cast<char*>(command));
}
查看更多
登录 后发表回答