Skip to content

Commit 0cf0203

Browse files
authored
Merge pull request #19 from OSVR/win-error-message
Added more useful error message when failing to load plugin on Windows.
2 parents db12e0d + 921cb80 commit 0cf0203

File tree

1 file changed

+38
-2
lines changed

1 file changed

+38
-2
lines changed

src/libfunctionality/LibraryHandleWin32.cpp

Lines changed: 38 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -26,23 +26,59 @@
2626

2727
// Internal Includes
2828
#include "LibraryHandleWin32.h"
29+
#include <libfunctionality/Exceptions.h>
2930

3031
// Library/third-party includes
3132
// - none
3233

3334
// Standard includes
35+
#include <string>
36+
3437
#define WIN32_LEAN_AND_MEAN
3538
#include <windows.h>
3639

3740
namespace libfunc {
3841

42+
static std::string getLastErrorMessage()
43+
{
44+
std::string error_msg;
45+
const auto error_code = GetLastError();
46+
if (ERROR_SUCCESS == error_code)
47+
return error_msg;
48+
49+
char* buffer = nullptr;
50+
51+
FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
52+
nullptr, error_code,
53+
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
54+
(LPTSTR)&buffer, 0, nullptr);
55+
56+
if (!buffer)
57+
return error_msg;
58+
59+
error_msg = buffer;
60+
LocalFree(buffer);
61+
62+
return error_msg;
63+
}
64+
3965
static void LibraryFreer(void *handle) {
4066
FreeLibrary(static_cast<HMODULE>(handle));
4167
}
4268

4369
LibraryHandle RAIILoadLibrary(std::string const &name) {
44-
return LibraryHandle(static_cast<void *>(LoadLibrary(name.c_str())),
45-
&LibraryFreer);
70+
auto lib = LibraryHandle(static_cast<void *>(LoadLibrary(name.c_str())),
71+
&LibraryFreer);
72+
if (!lib) {
73+
const auto error_msg = getLastErrorMessage();
74+
if (error_msg.empty()) {
75+
throw exceptions::CannotLoadPlugin(name);
76+
} else {
77+
throw exceptions::CannotLoadPlugin(name, error_msg.c_str());
78+
}
79+
}
80+
81+
return lib;
4682
}
4783

4884
} // end of namespace libfunc

0 commit comments

Comments
 (0)