Home  >  Article  >  Backend Development  >  What are the function calling conventions in C++?

What are the function calling conventions in C++?

PHPz
PHPzOriginal
2024-04-12 13:51:02529browse

Calling conventions in C define how function arguments are passed and values ​​are returned, including cdecl, fastcall, thiscall, and stdcall. In practice, the stdcall calling convention can be used to load and call functions in a DLL.

C++ 中函数调用约定有哪些?

C Function Calling Convention

In C, the calling convention defines how arguments to a function are passed and returned. Different calling conventions have different trade-offs in terms of performance, memory usage, and code portability.

Common calling conventions

  • cdecl (also known as stdcall): Applicable to Windows and Linux, parameters are pushed from right to left Stack, pop from left to right.
  • fastcall: Only used in Windows, the first two parameters are passed through registers, and the other parameters are pushed onto the stack.
  • thiscall: Used in object-oriented programming for member functions, the this pointer is passed through a register as the first parameter.
  • stdcall: Similar to cdecl, but uses Windows-style name decoration.

Practical case

The following C code demonstrates the use of stdcall to call a function:

#include <windows.h> // 只适用于 Windows

typedef void (WINAPI *pfnPrintString)(const char*);

int main()
{
    // 加载 DLL 并获取函数指针
    HMODULE hDll = LoadLibrary("mydll.dll");
    pfnPrintString PrintString = (pfnPrintString)GetProcAddress(hDll, "PrintString");

    // 调用函数,传递参数
    PrintString("Hello, world!");

    // 卸载 DLL
    FreeLibrary(hDll);

    return 0;
}

In this example, stdcall is used to call The convention is to load and call the PrintString function from the DLL.

The above is the detailed content of What are the function calling conventions in C++?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn