-
Notifications
You must be signed in to change notification settings - Fork 4
/
dylib.cpp
95 lines (76 loc) · 1.68 KB
/
dylib.cpp
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
#include "os.h"
#include <stdlib.h>
#ifdef __unix__
#include <dlfcn.h>
static mutex dylib_lock;
dylib* dylib::create(const char * filename, bool * owned)
{
dylib_lock.lock();
dylib* ret=NULL;
if (owned)
{
ret=(dylib*)dlopen(filename, RTLD_LAZY|RTLD_NOLOAD);
*owned=(!ret);
if (ret) return ret;
}
if (!ret) ret=(dylib*)dlopen(filename, RTLD_LAZY);
dylib_lock.unlock();
return ret;
}
void* dylib::sym_ptr(const char * name)
{
return dlsym((void*)this, name);
}
funcptr dylib::sym_func(const char * name)
{
funcptr ret;
*(void**)(&ret)=dlsym((void*)this, name);
return ret;
}
void dylib::release()
{
dlclose((void*)this);
}
#endif
#ifdef _WIN32
#undef bind
#include <windows.h>
#define bind bind_func
static mutex dylib_lock;
dylib* dylib::create(const char * filename, bool * owned)
{
dylib_lock.lock();
dylib* ret=NULL;
if (owned)
{
if (!GetModuleHandleEx(0, filename, (HMODULE*)&ret)) ret=NULL;
*owned=(!ret);
}
if (!ret)
{
//this is so weird dependencies, for example winpthread-1.dll, can be placed beside the dll where they belong
char * filename_copy=strdup(filename);
char * filename_copy_slash=strrchr(filename_copy, '/');
if (!filename_copy_slash) filename_copy_slash=strrchr(filename_copy, '\0');
filename_copy_slash[0]='\0';
SetDllDirectory(filename_copy);
free(filename_copy);
ret=(dylib*)LoadLibrary(filename);
SetDllDirectory(NULL);
}
dylib_lock.unlock();
return ret;
}
void* dylib::sym_ptr(const char * name)
{
return (void*)GetProcAddress((HMODULE)this, name);
}
funcptr dylib::sym_func(const char * name)
{
return (funcptr)GetProcAddress((HMODULE)this, name);
}
void dylib::release()
{
FreeLibrary((HMODULE)this);
}
#endif