Re: c++ class in a DLL
"PaulH" <paul.heil@gmail.com> wrote in message
news:af1283fe-2b92-4483-93f3-bb4ad3d042c3@s12g2000prg.googlegroups.com...
The header file looks basically like this (below). So, I just
dynamically load the library, get function pointers to the Get() and
Destroy() methods, and that's how I access the class.
#ifdef MY_EXPORTS
#define MY_API __declspec( dllexport )
#else
#define MY_API __declspec( dllimport )
#endif
#ifdef __cplusplus
extern "C" {
#endif
class MY_API CMyAPI {
public:
virtual BOOL MyFunc1() = 0;
virtual BOOL MyFunc2() = 0;
virtual BOOL MyFunc3() = 0;
virtual BOOL MyFunc4() = 0;
};
MY_API CMyAPI* CreateClass();
MY_API void DestroyClass( CMyAPI* pCtrl );
typedef CMyAPI* ( *PFN_GET_MY_CLASS )();
typedef void ( *PFN_DESTROY_MY_CLASS )( CMyAPI* );
#ifdef __cplusplus
};
#endif
Why the "extern C"? I don't know the consequences, but I wouldn't have
put that around the declaration of a C++ class.
Why the CreateClass and destroy class instead of constructor and destructor?
My problem is that if I add a new function, MyNewFunc(), to the class
in the DLL and then try to run a program compiled with an older
version of the header file, when I try to call MyFunc2(), or
something, I may end up calling MyNewFunc() instead!
Well yes.
What do I need to do to ensure the class functions always point to the
right place in the DLL?
Use the same header file in the calling module as you use in the DLL.
Otherwise you have different classes of the same name in the two modules -
not a recipe for happiness.
I do this with hundreds of classes, in MFC projects with dependencies set up
in the Visual Studio solution/workspace. If I change the header it gets
recompiled in all of them. I also define the digits of a VERSIONINFO
resource in a common header file, so that if anyone ever has a problem they
can check the the version numbers of the EXE and DLLs all match exactly.
[To date, no-one ever has managed to install incompatible versions, but I
have used this a few times to get people to check, thus ruling out this as
the source of the problem!]
Dave
--
David Webber
Author of 'Mozart the Music Processor'
http://www.mozart.co.uk
For discussion/support see
http://www.mozart.co.uk/mozartists/mailinglist.htm