Search code examples
c++windowsdlldllimportdllexport

How to use exported class from DLL


Hey I'm trying to write a Game-Engine and I was trying to export a class in a Dll and was trying to use it in my main code. Like using loadlibrary() function. I know how to export and use functions to and from Dll. But I want to export classes and then use them just like I use functions. I don't want to include <headers> for that class and then use it. I want it to be run-time. I have the following code for a very simple class that I was using to just experiment with it.

#ifndef __DLL_EXP_
#define __DLL_EXP_

#include <iostream>

#define DLL_EXPORT __declspec(dllexport)

class ISid
{
public:
virtual void msg() = 0;
};

class Sid : public ISid
{
void msg()
{
    std::cout << "hkjghjgulhul..." << std::endl;
}
};

ISid DLL_EXPORT *Create()
{
return new Sid();
}

void DLL_EXPORT Destroy(ISid *instance)
{
   delete instance;
}

#endif

How do I use this in my main code? Any help will be really appreciated. In case if it's important I'm on Visual Studio 2012.


Solution

  • If I understand the problem is not that you do not know how to load the class but cannot quite imagine how to use it afterwards? I cannot help with the syntax because I am used to shared objects dynamic loading, not dll but the usecase is the following:

    // isid.h that gets included everywhere you want to use Sid instance
    class ISid
    {
    public:
        virtual void msg() = 0;
    };
    

    If you want to use dynamic loaded code, you still have to know its interface. That is why I suggest you move the interface into a regular not-dll header

    // sid.h
    #ifndef __DLL_EXP_
    #define __DLL_EXP_
    
    #include <iostream>
    #include "isid.h" // thus you do not know what kind of dll you are loading, but you are well aware of the interface
    
    #define DLL_EXPORT __declspec(dllexport)
    class Sid : public ISid
    {
    void msg()
    {
        std::cout << "hkjghjgulhul..." << std::endl;
    }
    };
    
    ISid DLL_EXPORT *Create()
    {
        return new Sid();
    }
    
    void DLL_EXPORT Destroy(ISid *instance)
    {
        delete instance;
    }
    
    #endif
    

    And then you do something like that:

    // main.cpp
    #include <sid.h>
    int main()
    {
     // windows loading magic then something like where you load sid.dll
    .....
    typedef ISid* (*FactoryPtr)();
    FactoryPtr maker = (FactoryPtr) dlsym(symHanlde, "Create");
    ISid* instance = (*maker)();
    instance->msg();
    ...
    }
    

    Sorry I cannot provide the dll code but I do not wish to learn windows dll interface now so I hope this helps as to understand my comment.