Creating a DLL using Visual Studio is pretty easy. Create a New Project, and specify DLL as application type.
A DLL may have a sort of main function, that is called at startup and it is a good place where to put initialization code. Let's see here a possible implementation for such a function, that we are about to use just to print a log message when the DLL process is loaded:
#include <iostream>
BOOL APIENTRY DllMain( HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved )
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
std::cout << "DLL process attached" << std::endl;
break;
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
To make available functions to the user code, we write an header file where we put the function declarations:
#pragma once
#ifndef XDLL_API
#define XDLL_API extern "C" __declspec(dllimport)
#endif
XDLL_API void f();
We define a symbol (here we call it XDLL_API) that is a declaration specification for the functions. When we include this header in the application using the DLL, XDLL_API has not previously defined, so we use the definition here available, that specify that the functions are "dllimport".
Here is how we define a function in a DLL:
#include <iostream>
// XDLL_API defined for export
#define XDLL_API extern "C" __declspec(dllexport)
#include "xDll.h"
void f()
{
std::cout << "Hello from DLL" << std::endl;
}
Before including the header file containg the prototypes, we provide an alternative definition for the XDLL_API symbol, that is going to be used in the DLL. Notice that in the function definition we don't even use it - it is not necessary, since the compiler is smart enough to match the declaration with the definition even if we don't duplicate the declaration specification.
Basically, that's all. We compile, and we have a DLL ready to be used by other applications.
No comments:
Post a Comment