QLibrary - import a class

后端 未结 1 1387
谎友^
谎友^ 2021-01-13 04:03

I have a QT library and I want to import it in another project.

Now, since I want that, even when I modify the library, the other project does not need to be compile

相关标签:
1条回答
  • 2021-01-13 04:19

    You cannot call methods on classes imported at runtime. This is because the compiler links these calls at compile-time and not at run-time (which it cannot do). A way out is provided by our good ol' friend, the vtable:

    You can, call virtual methods on classes implementing an interface (the interface is not "imported" at runtime). That means to define a class defining the interface using virtual (possibly pure virtual) methods. TestDLL_lib would then inherit that interface, implementing the methods. You would refer to the TestDLL_lib instance via that interface and call methods trough that interface, effectively calling them trough the vtable of the interface, which is "superseded" by TestDLL_libs vtable.

    Don't forget to make your d'tor virtual and to add a virtual dtor to the interface. If you don't do that you cannot safely delete instance trough the interface pointer.

    I might also explain why you can access members, but not call functions on "imported" classes. The members are accessed by memory location, and the memory location is solely defined by the compiler. Thus the compiler generates the code to access members without ever referring to any of the classes' symbols (methods and so on). This in turns leads to no linkage dependency. Note however that you would need to recompile both the DLL and the application using the DLL if you change the class, e.g. adding or removing a member, since that changes the memory layout.

    class TestInterface
    {
    public:
        virtual ~TestInterface()
        {
        }
    
        virtual int getValues() = 0;
    }
    
    class TESTDLL_LIBSHARED_EXPORT TestDLL_lib : public TestInterface
    {
    
    public:
        TestDLL_lib();
        virtual ~TestDLL_lib();
    
        int a;
        int b;
        int c;
    
        int getValues() override; // MSVC may not support "override"
    }; 
    
    // return pointer to interface!
    // TestDLL_lib can and should be completely hidden from the application
    extern "C" TESTDLL_LIBSHARED_EXPORT TestInterface *create_TestDLL_lib()
    {
        return new TestDLL_lib();
    }
    
    0 讨论(0)
提交回复
热议问题