summaryrefslogtreecommitdiff
path: root/src/lua-plugin.cc
blob: e80f0f890f45c6d421ea33507380856a2a096857 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#include <lua-plugin.h>

#if defined(_WIN32)
#define SHARED_EXT "dll"
#elif defined(__APPLE__)
#define SHARED_EXT "dylib"
#else
#define SHARED_EXT "so"
#endif

typedef void(*init_ptr_t)(Lua *);

#if defined(_WIN32)
#include <windows.h>

void LuaLoadPlugin(const String & _fname, Lua * L) throw (GeneralException) {
    HMODULE handle;
    String fname = _fname + "." SHARED_EXT;

    Base::printm(M_INFO, "Loading library " + fname + "\n");

    if (!(handle = LoadLibraryEx(fname.to_charp(), NULL, LOAD_WITH_ALTERED_SEARCH_PATH)) &&
	!(handle = LoadLibraryEx(fname.to_charp(), NULL, NULL))) {
	throw GeneralException("File not found or error loading shared object file: " + fname + "; Error #" + String((int) GetLastError()));
    }
    
    init_ptr_t init_ptr = (init_ptr_t) GetProcAddress(handle, "init_plugin");

    if (!init_ptr) {
	throw GeneralException("No init pointer on plugin " + fname);
    }
    
    Base::printm(M_INFO, "Library loaded, init ptr = %p\n", init_ptr);
    
    init_ptr(L);
}
#else
#include <dlfcn.h>

void LuaLoadPlugin(const String & fname, Lua * L) throw (GeneralException) {
    void * handle = dlopen(("./" + fname + "." SHARED_EXT).to_charp(), RTLD_NOW | RTLD_GLOBAL);
    
    Base::printm(M_INFO, "Loading library " + fname + "\n");

    if (!handle) {
	throw GeneralException("File not found or error loading shared object file: " + fname + "; " + dlerror());
    }
    
    init_ptr_t init_ptr = (init_ptr_t) dlsym(handle, "init_plugin");
    
    if (!init_ptr) {
	throw GeneralException("No init pointer on plugin " + fname);
    }
    
    Base::printm(M_INFO, "Library loaded, init ptr = %p\n", init_ptr);
    
    init_ptr(L);
}
#endif