Dynamically importing a C++ class from a DLL

前端 未结 5 1969
失恋的感觉
失恋的感觉 2020-12-31 06:34

What is the correct way to import a C++ class from a DLL? We\'re using Visual C++.

There\'s the dllexport/exports.def+LoadLibrary+GetProcAddress trifecta, but it do

相关标签:
5条回答
  • 2020-12-31 06:50

    You need to add the following:

    extern "C"
    {
    ...
    }
    

    to avoid function mangling.

    you might consider writing two simple C functions:

    SomeClass* CreateObjectInstace()
    {
        return new SomeClass();
    }
    
    void ReleaseObject(SomeClass* someClass)
    {
       delete someClass;
    }
    

    By only using those functions you can afterward add/change functionality of your object creation/deletion. This is sometimes called a Factory.

    0 讨论(0)
  • 2020-12-31 06:52

    I normally declare an interface base class, use this declaration in my application, then use LoadLibrary, GetProcAddress to get the factory function. The factor always returns pointer of the interface type.

    Here is a practical example, exporting an MFC document/view from a DLL, dynamically loaded

    0 讨论(0)
  • 2020-12-31 06:59

    Check out this question. Basically, there are two ways. You can mark the class using _dllexport and then link with the import library, and the DLL will be loaded automatically. Or if you want to load the DLL dynamically yourself, you can use the factory function idea that @titanae suggested

    0 讨论(0)
  • 2020-12-31 07:02

    Found the solution at http://www.codeproject.com/KB/DLL/XDllPt4.aspx

    Thanks for your efforts guys & girls

    0 讨论(0)
  • 2020-12-31 07:02

    dllexport/dllimport works, place it before your class name in the header file and you're good to go.

    Typically you want to use dllexport in the dll, and dllimport in the exe (but you can just use dllexport everywhere and it works, doing it 'right' makes it tinily faster to load).

    Obviously that is for link-time compilation. You can use /delayload linker directive to make it 'dynamic', but that's probably not what you want from the subject line.

    If you truly want a LoadLibrary style loading, you're going to have to wrap your C++ functions with "extern C" wrappers. The problem is because of name mangling, you could type in the fully-mangled name and it'd work.

    The workarounds are generally to provide a C function that returns a pointer to the correct class - COM works this way, as it exports 4 C functions from a dll that are used to get the interface methods inside the object in the dll.

    0 讨论(0)
提交回复
热议问题