In C ++, we can use _ declspec (dllexport) to export the function as a Dll for other programs. For example:
_ Declspec (dllexport) int add (int a, int B );
In this way, if the dll is called by a c ++ program (the same compiler version), there is no problem. However, if you call this dll as a program in other languages (such as C # and VB), an error occurs. The reason is that there is a function overload in C ++ that allows the function to have multiple names. Therefore, when the compiler generates a dll, it performs name conversion for certain algorithms. For example, the actual name of the add function is as follows.
Therefore, the function cannot be found directly through the function name add, resulting in call failure. To solve this problem, we often add an extern "C" before the function to use the C-Way Function naming rule.
Extern "C" _ declspec (dllexport) int add (int a, int B );
In this way, the function name is "add.
In this way, we need to add the "extern" C "_ declspec (dllexport)" long string declaration to each function signature. If you need to export a large number of functions, it is very cumbersome and ugly. To simplify this process, MS introduced the def file for our convenience.
Using the Def file is relatively simple. You only need to add a def file to the project, and then place the function to be exported in the def file.
A simple example of the Def file is as follows:
LIBRARY
EXPORTS
Add
Finally, remember to select the def file used in the linker option (this option is automatically added when you add the def file by default, and you do not need to manually change it ).
In this way, our function can still use the default int add (int a, int B); form without adding the heap prefix, however, the export method is still C-form function definition.
Finally, it is worth mentioning that the default call Method for C/C ++ is _ cdecl. In this way, the caller needs to clear the function stack. If other non-C ++ programs are provided for external APIs, the caller will not be able to clear the stack and make an error (C # will directly report the function declaration Mismatch Error ). Therefore, when providing APIs externally, you should also declare the interface as _ stdcall so that the api functions can be cleaned up by themselves. This is also the reason why a WINAPI macro is added before Windows APIs.
Def file has many other advanced usage, for further understanding, you can refer to the official documents of MS: http://msdn.microsoft.com/zh-cn/library/28d6s79h (v = vs.80). aspx