How can I import dll of a C++ class inside a namespace

accfews picture accfews · Feb 15, 2012 · Viewed 10.1k times · Source

I read some documents which gives simple examples on functions compatible with C.

__declspec(dllexport) MyFunction();

I'm okey with that. I write a small application uses the functions of this dll. I used explicit linking with

LoadLibrary() 

function. C style functions work without problems. But when i write my class as

namespace DllTest
{
class Test
{
public:
    __declspec(dllexport) Test();
    __declspec(dllexport) void Function( int );
    __declspec(dllexport) int getBar(void);
private:
    int bar;
};

}
#endif

it compiles well and Dll is created. While working with C style functions i was simply taking a function pointer from LoadLibrary() and GetProcAddress(...) functions.

My previous usage is

typedef void (*Function)(int);

int main()
{
   Function _Function;
   HINSTANCE hInstLibrary = LoadLibrary(TEXT("test.dll"));

   if (hInstLibrary)
   {
      _Function = (Function)GetProcAddress(hInstLibrary,"Function");
     if (_Function)
     {
        // use the function

But now i have no idea how can i instantiate my class? How can i use explicit linkage or implicit linkage?

Any help with a code sample would be appreciated.

Answer

mfontanini picture mfontanini · Feb 15, 2012

If you're trying to instantiate a class, then you need to know its structure on compilation time. You can achieve this by creating an abstract class that defines the instance methods that the imported class will have to redefine. For example:

//interface.h

class TestInterface
{
public:
     virtual void Function( int ) = 0;
     virtual int getBar(void) = 0;
};

Afterwards, in your DLL, you can include interface.h, inherit TestInterface and redefine the pure-virtual methods:

//test.h
namespace DllTest {
    class Test : public TestInterface
    {
    public:
         Test();
         void Function( int );
         int getBar(void);
    private:
        int bar;
    };
};

You could then define a function in your DLL which allocates a Test object:

extern "C" __declspec(dllexport) TestInterface *allocate_test() {
    return new DllTest::Test();
}

And finally, when you import the DLL, look for the symbol "allocate_test" and use it:

TestInterface *(*test_fun)() = (TestInterface *(*test_fun)())GetProcAddress(hInstLibrary,"allocate_test");
TestInterface *test_ptr = test_fun();
test_ptr->Function(12); //use you object