配置插件的配置文件:pluginLibraryList.json
获得插件列表
std::optional<std::vector<std::filesystem::path>> getPluginLibraryList()
{
auto resDir = GetResourcesDirectory();
auto libsDir = GetLibsDirectory();
auto pluginLibraryList = resDir / "pluginLibraryList.json";
Json::Value pluginLibraryListJson;
std::error_code ec;
if ( std::filesystem::exists( pluginLibraryList, ec ) )
{
auto readRes = deserializeJsonValue( pluginLibraryList );
if ( !readRes.has_value() )
spdlog::error( readRes.error() );
else
pluginLibraryListJson = readRes.value();
#if _WIN32
if ( pluginLibraryListJson["Windows"].isArray() )
pluginLibraryListJson = pluginLibraryListJson["Windows"];
#else
if ( pluginLibraryListJson["Linux"].isArray() )
pluginLibraryListJson = pluginLibraryListJson["Linux"];
#endif
else
{
spdlog::error( "Json has no Value for current OS!" );
return std::nullopt;
}
}
else
spdlog::warn( "Failed to open json config file " + utf8string( pluginLibraryList ) + " with " + systemToUtf8( ec.message() ) );
if ( pluginLibraryListJson.isArray() )
{
std::vector<std::filesystem::path> res;
for ( auto& v : pluginLibraryListJson )
{
#if _WIN32
res.push_back( libsDir / ( v.asString() + ".dll" ) );
#elif defined __APPLE__
res.push_back( libsDir / ( "lib" + v.asString() + ".dylib" ) );
#else
res.push_back( libsDir / ( "lib" + v.asString() + ".so" ) );
#endif
}
return res;
}
else
{
spdlog::warn( "Json file with viewer plugin library list was not found or corrupted. Empty list returned." );
return {};
}
}
加载插件
void ViewerSetup::setupExtendedLibraries() const
{
const auto pluginLibraryList = getPluginLibraryList();
if ( !pluginLibraryList )
return;
for (const auto& pluginLib : *pluginLibraryList)
{
#if _WIN32
auto result = LoadLibraryW( pluginLib.wstring().c_str() );
if ( !result )
{
auto error = GetLastError();
spdlog::error( "Load library {} error: {}", utf8string( pluginLib ), error );
assert( false );
}
#else
void* result = dlopen( utf8string( pluginLib ).c_str(), RTLD_LAZY );
if ( !result )
{
auto error = dlerror();
spdlog::error( "Load library {} error: {}", utf8string( pluginLib ), error );
assert( false );
}
#endif
}
}