简体   繁体   中英

C++ Function Type?

I'm new to, and learning C++ (know a lot of Java) and the following code confuses me...

在此输入图像描述

I know this code fragment is dealing with a pointer-to-function (it's a callback, that makes sense) but what is throwing me off is the argument between the return type and the function name. What the bloody hell is that?

It looks like a type of function, but I have never heard of that and even after searching and reading about pointer-to-functions I was not able to find anything mentioning that functions could have a type.

If this is true, how does one define a function type?

Thanks, -Cody

GLFWCALL is not a type, it's a macro which is expanded to a calling convention specific to the platform, or an empty string. Here's a trimmed fragment of glfw.h:

#if defined(_WIN32) && defined(GLFW_BUILD_DLL)
 #define GLFWCALL     __stdcall
#elif defined(_WIN32) && defined(GLFW_DLL)
 #define GLFWCALL     __stdcall
#else
 /* We are either building/calling a static lib or we are non-win32 */
 #define GLFWCALL
#endif

Using a correct calling convention is important on x86/win32, since some of them expect the stack to be cleaned by callee and others by the caller. There can also be differences in the order of passing the arguments.

On Windows, GLFWCALL is a macro for __stdcall , and on other platforms, it's a macro for nothing.

__stdcall implements a particular calling convention, and is a compiler extension on top of normal C or C++.

Macros are pieces of code that do replacements on your code before the lexer and parser of your compiler interact with them.

The GLFWCALL is a macro that can expand to a calling convention if one is needed. Because this function will be called by external code, it has to use the calling convention that external code expects. For example, if the function puts its return value on the stack and the external code expects it in a register, boom.

The question marked part of the function signature is a preprocessor macro that is defined somewhere else in the header. Certain features on certain platforms have extra requirements.

For example functions in DLL files on the Windows platform often make use of the __declspec(dllexport) modifier but when the same header is included in a user's project they need to use __declspec(dllimport). Using a preprocessor macro for that purpose means they can just use that macro on all relevant functions and simply define the macro differently when compiling their own DLL or a user's DLL and on platforms where __declspec is irrelevant it can be defined to nothing. There are many other reasons for macros like that one.

In this particular case you can effectively pretend that macro is blank and ignore it entirely.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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