Skip to content

Commit

Permalink
Keeping the dll path cookie during class instantiation (#147)
Browse files Browse the repository at this point in the history
  • Loading branch information
WeilongWen authored Oct 27, 2024
1 parent 38799be commit 32373dc
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 25 deletions.
4 changes: 4 additions & 0 deletions include/fmi4cpp/fmi2/fmi2_library.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,10 @@ class fmi2_library

fmi2FreeInstanceTYPE* fmi2FreeInstance_;

private:
#ifdef _WIN32
DLL_DIRECTORY_COOKIE dllDirectoryCookie_ = nullptr;
#endif
protected:
fmi2Status lastStatus_;
DLL_HANDLE handle_ = nullptr;
Expand Down
21 changes: 21 additions & 0 deletions src/fmi4cpp/fmi2/fmi2_library.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,20 @@ fmi2_library::fmi2_library(const std::string& modelIdentifier, const std::shared

MLOG_DEBUG("Loading shared library '" + std::filesystem::path(libName).stem().string() + get_shared_library_extension() + "'");

#ifdef _WIN32
std::string dllDirectory;
fmi4cpp::fs::path path(libName);

if (path.has_parent_path()) {
dllDirectory = path.parent_path().string();
}

if (!dllDirectory.empty()) {
std::wstring wDllDirectory(dllDirectory.begin(), dllDirectory.end());
dllDirectoryCookie_ = AddDllDirectory(wDllDirectory.c_str());
}
#endif

handle_ = load_library(libName);

if (!handle_) {
Expand Down Expand Up @@ -419,6 +433,13 @@ void fmi2_library::free_instance(fmi2Component c)

fmi2_library::~fmi2_library()
{
#ifdef _WIN32
if (dllDirectoryCookie_) {
RemoveDllDirectory(dllDirectoryCookie_);
dllDirectoryCookie_ = nullptr;
}
#endif

if (handle_) {
if (!free_library(handle_)) {
MLOG_ERROR(getLastError());
Expand Down
27 changes: 2 additions & 25 deletions src/fmi4cpp/library_helper.hpp
Original file line number Diff line number Diff line change
@@ -1,39 +1,16 @@

#ifndef FMI4CPP_LIBRARYHELPER_HPP
#define FMI4CPP_LIBRARYHELPER_HPP

#include <fmi4cpp/dll_handle.hpp>

#include <filesystem>
#include <sstream>

namespace fmi4cpp
{

inline DLL_HANDLE load_library(const std::string& libName)
{
std::string dllDirectory;

#ifdef _WIN32
std::filesystem::path path(libName);
if (path.has_parent_path()) {
dllDirectory = path.parent_path().string();
}

DLL_DIRECTORY_COOKIE dllDirectoryCookie = nullptr;
if (!dllDirectory.empty()) {
std::wstring wDllDirectory(dllDirectory.begin(), dllDirectory.end());
dllDirectoryCookie = AddDllDirectory(wDllDirectory.c_str());
}

DLL_HANDLE handle = LoadLibrary(libName.c_str());

if (dllDirectoryCookie) {
RemoveDllDirectory(dllDirectoryCookie);
}

return handle;

#ifdef WIN32
return LoadLibrary(libName.c_str());
#else
return dlopen(libName.c_str(), RTLD_NOW | RTLD_LOCAL);
#endif
Expand Down

0 comments on commit 32373dc

Please sign in to comment.