1 Minimum steps to create a simple DLL with VS2019
- Create a "windows DLL" type project in VS2019
- Delete all auto generated .h and .cpp files
- Disable Precompiled Headers by
- Project---Property---Configuration Properties---C/C++---Precompiled Headers---Precompiled Header = "Not Using Precompiled Headers"
- Add a new c file called "mydll.c"
/* mydll.c */
int __stdcall Add(int a, int b)
{
return a + b;
}
- Add a "Module-Defination File" named "mydll.def" and make sure it's used by the linker by
- Project---Property---Configuration Properties---Liner---Input---Module Definition File = "mydll.def"
; mydll.def
LIBRARY
EXPORTS
Add
- Compile and done.
- two files will be generated
- mydll.lib
- mydll.dll
2 dllexport and traps
By using the Module Definition file, mydll.def, we avoided name mangling in our example.
But if you don't use a Module Definition file, a lot of trouble will occur.
#ifdef __cplusplus
#define EXPORT extern "C" __declspec (dllexport)
#else
#define EXPORT __declspec (dllexport)
#endif
EXPORT int __stdcall Add(int a, int b);
C name manging
Unfortunately, even with "__declspec (dllexport)", the C name manging is still there.
The genegrated dll will have the exported function name as "_Add@8" instead of "Add".
This is not a problem when mydll.dll is used via its companioned mydll.lib. But it does cause issues when the code tries to use "LoadLibrary() and GetProcAddress()" to load the dll at runtime.
dllexport exposes the function as it is decorated by the compiler. For example, if the function is a C++ function, it will be exposed with C++ name mangling. If the function is a C function, or has been declared as
extern "C"
, it will be exposed with C name mangling. To expose the function under its unmangled name (or to expose it via an alternate name), use a .def file (EXPORTS keyword).
No comments:
Post a Comment