Using Q_DECLARE_METATYPE with a DLL that can be loaded multiple times

Using Qt 4.8 with C ++. I work with application plugins that load and unload at runtime. The same plugin can be downloaded several times during the life of the application. One of these plugins uses Q_DECLARE_METATYPE for some types that need to be stored in QVariant . When the plugin is reloaded later, the old declaration still points to the original memory space of the now unloaded library. This leads to access violations when Qt tries to create a QVariant from a QVariant meta type. We have already considered a similar problem with qRegisterMetaType() : we register meta types when loading a library and unregister these types immediately before unloading the library. Unfortunately, this does not seem to be a choice, but not a registration of meta types.

How can we effectively handle cases where a library declaring a meta type is loaded and unloaded several times?

+6
source share
2 answers

To extend the answer to Kuba Ober, you need to unregister the meta type by calling QMetaType::unregisterType() ( http://doc.qt.io/qt-4.8/qmetatype.html#unregisterType ) with your type name before uploading your Dll. You should be able to unregister declared meta types in the same place where you unregister registered types with qRegisterMetaType<T> . This should cause the Qt Meta Object system to be in a clean state (as far as your unloaded plug-in is concerned), so the next time the plug-in is loaded, new meta-type identifiers will be created. In particular, when the DLL loads again, the Q_DECLARE_METATYPE macro will register your type again, this time with the new metatype_id and QVariant will no longer give you access violations.

+1
source

When you look at what Q_DECLARE_METATYPE does, you see that it declares the specialization of the QMetaTypeId<T> template class as one qt_metatype_id() member, which uses a static variable to store the qRegisterMetaType value. If, as you claim, you can unregister the metatype, you are all set.

+1
source

Source: https://habr.com/ru/post/955447/


All Articles