Refactor command handling to library/
[lsnes.git] / src / core / loadlib.cpp
blob655557ac2b4393319bb5d45a5337287dea805a0d
1 #include "core/loadlib.hpp"
2 #include "core/command.hpp"
3 #include <stdexcept>
4 #include <sstream>
6 namespace {
7 function_ptr_command<arg_filename> load_lib(lsnes_cmd, "load-library", "Load a library",
8 "Syntax: load-library <file>\nLoad library <file>\n",
9 [](arg_filename args) throw(std::bad_alloc, std::runtime_error) {
10 try {
11 load_library(args);
12 } catch(std::exception& e) {
13 std::ostringstream x;
14 x << "Can't load '" << std::string(args) << "': " << e.what();
15 throw std::runtime_error(x.str());
17 });
20 #if !defined(NO_DLFCN) && !defined(_WIN32) && !defined(_WIN64)
21 #include <dlfcn.h>
22 #include <unistd.h>
23 void load_library(const std::string& filename)
25 char buffer[16384];
26 getcwd(buffer, 16383);
27 std::string _filename = filename;
28 if(filename.find_first_of("/") >= filename.length())
29 _filename = buffer + std::string("/") + filename;
30 void* h = dlopen(_filename.c_str(), RTLD_LOCAL | RTLD_NOW);
31 if(!h)
32 throw std::runtime_error(dlerror());
34 extern const bool load_library_supported = true;
35 #ifdef __APPLE__
36 const char* library_is_called = "Dynamic Library";
37 #else
38 const char* library_is_called = "Shared Object";
39 #endif
40 #elif defined(_WIN32) || defined(_WIN64)
41 #include <windows.h>
42 void load_library(const std::string& filename)
44 char buffer[16384];
45 GetCurrentDirectory(16383, buffer);
46 std::string _filename = filename;
47 if(filename.find_first_of("/\\") >= filename.length())
48 _filename = buffer + std::string("/") + filename;
49 HMODULE h = LoadLibraryA(_filename.c_str());
50 if(!h) {
51 int errcode = GetLastError();
52 char errorbuffer[1024];
53 if(FormatMessage(FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_FROM_SYSTEM, NULL, errcode, 0,
54 errorbuffer, sizeof(errorbuffer), NULL))
55 throw std::runtime_error(errorbuffer);
56 else {
57 std::ostringstream str;
58 str << "Unknown system error (code " << errcode << ")";
59 throw std::runtime_error(str.str());
63 extern const bool load_library_supported = true;
64 const char* library_is_called = "Dynamic Link Library";
65 #else
66 void load_library(const std::string& filename)
68 throw std::runtime_error("Library loader not supported on this platform");
70 extern const bool load_library_supported = false;
71 const char* library_is_called = NULL;
72 #endif