Using Interfaces with Dlls

Published February 22, 2000 by Gaz Iqbal, posted by Myopic Rhino
Do you see issues with this article? Let us know.
Advertisement
I've seen a quite a few posts on message boards and forums asking how to get "classes" working with DLLs (Dynamic Link Libraries). The issue is that DLLs use standard C-style linkage while C++ code generates C++ style linkage with different name decoration so you can't directly export member functions from a C++ class and then call them from client code. However it can be done by making use of interfaces which are shared between the DLL and the client. This method is very powerful and elegant since the client only sees the abstract interface, and the actual class object could be any class that implements that interface. This enables the client to load whatever DLL it wants and polymorphically treat the interfaces it receives from them as the same. Microsoft's COM (Component Object Model) uses the same idea with a lot of added functionality, however we usually don't need the all the features and overhead of COM in game oriented projects. This article will discuss how to use "classes" using COM style interfaces when using run-time linking or just as when using load-time linking.

Before we start, you should be aware that all DLLs can have a DllMain() implementation. This is similar to WinMain, or main() in terms that its the entry point function for the DLL. The Operating System automatically calls this if its defined whenever the DLL is loaded, freed or when any threads attach or detach to it. If all you need is to make the DLL aware of any of these events, then this is all you should need. Usually however, this function doesn't lend itself to provide any other use apart from getting the DLL to handle the aforementioned events. To get more functionality out of a DLL, the programmer is mostly better off exporting his own set of functions. There are two methods to using DLLs from client code. The client can make use of loadtime linking or runtime linking.


[size="5"]LoadTime Linking

In loadtime linking the OS automatically loads the DLL for you when the program is starting up. However this requires that the client code be linked to the .lib file (library file) provided with the DLL during compilation. The .lib file defines all the items that the DLL exports. These may include normal C-style functions, or even classes. All the client code needs to do is link to the .lib file and include the header provided by the DLL and the OS will automatically load everything for you. As you can see, this method seems very easy to use, since everything is transparent. However it introduces dependencies so that the client code will have to be recompiled each time the DLL code changes and generates a new .lib file. This may or may not be a concern for your project. The DLL can define functions it wants to export using two methods. The standard way is to use .def files. The .def file of a DLL is simply a listing of the names of functions it wants to export.

//============================================================
//Dlls .def file

LIBRARY myfirstdll.dll
DESCRIPTION 'My first DLL'
EXPORTS
MyFunction


//============================================================
//Dlls header file which would also be included in client code

bool MyFunction(int parms);


//============================================================
//Dlls implementation of the function

bool MyFunction(int parms)
{
//do stuff
............
}
It goes without saying that there can only be one MyFunction in the global namespace of your DLL. The second way is Microsoft specific, but is more powerful as you can not only export function, but also Classes and variables. Lets take a look at some code which generated by creating a DLL using the VisualC++ AppWizard. The comments generated are quite enough to explain how this works

//============================================================
//Dlls header file which would also be included in client code


/*
The following ifdef block is the standard way of creating macros which make exporting
from a DLL simpler. All files within this DLL are compiled with the MYFIRSTDLL_EXPORTS
symbol defined on the command line. this symbol should not be defined on any project
that uses this DLL. This way any other project whose source files include this file see
MYFIRSTDLL_API functions as being imported from a DLL, where as this DLL sees symbols
defined with this macro as being exported.
*/

#ifdef MYFIRSTDLL_EXPORTS
#define MYFIRSTDLL_API __declspec(dllexport)
#else
#define MYFIRSTDLL_API __declspec(dllimport)
#endif

// This class is exported from the test2.dll
class MYFIRSTDLL_API CMyFirstDll {
public:
CMyFirstDll(void);
// TODO: add your methods here.
};

extern MYFIRSTDLL_API int nMyFirstDll;

MYFIRSTDLL_API int fnMyFunction(void);
When you compile the DLL the MYFIRSTDLL_EXPORTS symbol is defined, and the __declspec(dllexport) keyword is prefixed to classes/variables or functions you want to be exported. And when the client code is being compiled the symbol is undefined and __declspec(dllimport) is prefixed to the items being imported from the DLL so that the client code knows where to look for them.

In both the methods outlined above, all the client code needs to do is to link to the myfirstdll.lib file during compilation and include the given header file which defines the functions and/or classes, variables being exported and it can use the items normally as if they had been declared locally. Now lets take a look at the other method of using DLLs, which I personally believe is more open-ended.


[size="5"]RunTime Linking

When using RunTime linking, the client doesn't rely on the OS but loads the DLL explicitly in the code when it wants to. Furthermore it doesnt need to link to any .lib files so you don't have to recompile the client just to link to a newer lib file. RunTime linking is powerful in the sense that YOU the programmer have the power to decide which DLL to load. Lets say you are writing a game which supports DirectX and OpenGL. Either you can just include all the code in the executable which might be hard to maintain if more than one person is working on it. Or you can seperate the DirectX code in one DLL and the OpenGL code in another and link to them statically so that they are loaded at LoadTime. But now all the code depends on eachother, and if you have a new DirectX DLL then you have to rebuild the executable as well. Apart from that, both DLLs will be automatically loaded when the program starts thus increasing your memory usage. The last, and in my opinion the best, idea is to let the executable decide which DLL to load once it starts. If you find that the system doesn't have OpenGL acceleration then you would load the DirectX DLL, otherwise you would load the OpenGL DLL. Thus RunTime linking reduces memory usage and dependencies. However the limitation here is only C style functions can be exported. Classes or variables cannot be loaded from a DLL when you load it during Runtime. But I'll show how to get around that by using Interfaces.

DLLs designed for RunTime linking usually use .def files to define the functions they will export. If you don't want to use .def files then you can just prefix the C functions to be exported with the __declspec(dllexport) keyword. Both of these methods accomplish the same thing. The client loads a DLL by passing the name of the DLL to the Win32 LoadLibrary() function. This returns a HINSTANCE handle which you should keep track of, as its needed when you want to unload the DLL. Once it has loaded the DLL, the client can get a pointer to any of the exported functions by calling GetProcAddress() with the function name.

//============================================================
//Dlls .def file

LIBRARY myfirstdll.dll
DESCRIPTION 'My first DLL'
EXPORTS
MyFunction

//============================================================
/*
Dlls implementation of the function
*/

bool MyFunction(int parms)
{
//do stuff
............
}

//============================================================
//Client code

/*
The function declaration really isn't required but the client
needs to be of the function parameters. These are usually
supplied in a header file accompanying the DLL. The extern C with
the function decleration tells the compiler to use C-style linkage.
*/

extern "C" bool MyFunction(int parms);
typedef bool (*MYFUNCTION)(int parms);

MYFUNCTION pfnMyFunc=0; //pointer to MyFunction

HINSTANCE hMyDll = ::LoadLibrary("myfirstdll.dll");

if(hMyDll != NULL)
{
//Get the functions address
pfnMyFunc= (MYFUNCTION)::GetProcAddress(hMyDll, "MyFunction");

//Release DLL if we werent able to get the function
if(pfnMyFunc== 0)
{
::FreeLibrary(hMyDll);
return;
}

//Call the Function
bool result = pfnMyFunc(parms);

//Release the DLL if we dont have any use for it now
::FreeLibrary(hMyDll);
}
As you can see the code is very straight forward. Lets see how to get "classes" working by building on the same concept. As mentioned earlier, there is no way to directly import classes from a DLL when using RunTime loading, so what we can do is to expose the "functionality" of a class by defining an interface which contains all of its public functions apart from the constructor and destructor. The interface will be a typical C/C++ structure containing only pure virtual functions. The actual class in the DLL will inherit from this struct and it will implement the functions defined in it. Now to allow access to this class from the client, all we need to do is to export a standard C-style function that instantiates the class, casts it to the interface so that the client can use it, and returns it. Another function should be exported that deletes the interface once the client is done with it. A sample implementation is given below.

//============================================================
//Dlls .def file

LIBRARY myinterface.dll
DESCRIPTION 'provides interface to I_MyInterface
EXPORTS
GetMyInterface
FreeMyInterface



//============================================================
//Shared header between Dll and Client which defines the interface
//I_MyInterface.h

struct I_MyInterface
{
virtual bool Init(int parms)=0;
virtual bool Release()=0;
virtual void DoStuff() =0;
};

/*
Declarations for the Dlls exported functions and typedef'ed function
pointers to make it easier to load them. Note the extern "C" which
tell the compiler to use C-style linkage for these functions
*/

extern "C"
{
HRESULT GetMyInterface(I_MyInterface ** pInterface);
typedef HRESULT (*GETINTERFACE)(I_MyInterface ** pInterface);

HRESULT FreeMyInterface(I_MyInterface ** pInterface);
typedef HRESULT (*FREEINTERFACE)(I_MyInterface ** pInterface);
}



//============================================================
//Dlls implementation of the interface
// MyInterface.h

class CMyClass: public I_MyInterface
{
public:
bool Init(int parms);
bool Release();
void DoStuff();

CMyClass();
~CMyClass();

//any other member funcs
............
private:
//any member vars
............
};

//============================================================
//Dlls exported functions which create and delete the interface
//Dllmain.h

HRESULT GetMyInterface(I_MyInterface ** pInterface)
{
if(!*pInterface)
{
*pInterface= new CMyClass;
return S_OK;
}
return E_FAIL;
}

HRESULT FreeMyInterface(I_MyInterface ** pInterface)
{
if(!*pInterface)
return E_FAIL;
delete *pInterface;
*pInterface= 0;
return S_OK;
}

//============================================================
//Client code


//How to load the interface and call functions

GETINTERFACE pfnInterface=0; //pointer to GetMyInterface function
I_MyInterface * pInterface =0; //pointer to MyInterface struct

HINSTANCE hMyDll = ::LoadLibrary("myinterface.dll");

if(hMyDll != NULL)
{
//Get the functions address
pfnInterface= (GETINTERFACE)::GetProcAddress(hMyDll,"GetMyInterface");

//Release Dll if we werent able to get the function
if(pfnInterface == 0)
{
::FreeLibrary(hMyDll);
return;
}

//Call the Function
HRESULT hr = pfnInterface(&pInterface);

//Release if it didnt work
if(FAILED(hr))
{
::FreeLibrary(hMyDll);
return;
}

//Interface was loaded, we can now call functions
pInterface->Init(1);
pInterface->DoStuff();
pInterface->Release();

//How to release the interface

FREEINTERFACE pfnFree = (FREEINTERFACE )::GetProcAddress(hMyDll,"FreeMyInterface");
if(pfnFree != 0)
pfnFree(&hMyDll);

//Release the DLL if we dont have any use for it now
::FreeLibrary(hMyDll);
}
Ths information should be enough to get you really comfortable when using DLLs. Feel free to contact me if you have any questions, corrections or improvements. Happy coding.

[email="skid@planetquake.com"]Gaz Iqbal[/email]
Cancel Save
1 Likes 0 Comments

Comments

Nobody has left a comment. You can be the first!
You must log in to join the conversation.
Don't have a GameDev.net account? Sign up!
Advertisement