summaryrefslogtreecommitdiffstatshomepage
path: root/src/lib/netlist/plib/pdynlib.cpp
blob: f7a651c353b04e6a80b748c77183c299ae37bfef (plain) (blame)
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
// license:GPL-2.0+
// copyright-holders:Couriersud

#include "pdynlib.h"

#ifdef _WIN32
#include "windows.h"
#else
#include <dlfcn.h>
#endif

#include <type_traits>

namespace plib
{
	using winapi_string = std::conditional<compile_info::unicode::value,
		pwstring, pu8string>::type;

dynlib::dynlib(const pstring &libname)
: m_lib(nullptr)
{
#ifdef _WIN32
	//fprintf(stderr, "win: loading <%s>\n", libname.c_str());
	if (!libname.empty())
		m_lib = LoadLibrary(winapi_string(putf8string(libname)).c_str());
	else
		m_lib = GetModuleHandle(nullptr);
#elif defined(__EMSCRIPTEN__)
	//no-op
#else
	//printf("loading <%s>\n", libname.c_str());
	if (!libname.empty())
		m_lib = dlopen(putf8string(libname).c_str(), RTLD_LAZY);
	else
		m_lib = dlopen(nullptr, RTLD_LAZY);
#endif
	if (m_lib != nullptr)
		set_loaded(true);
	//else
	//  printf("library <%s> not found: %s\n", libname.c_str(), dlerror());
	}

dynlib::dynlib(const pstring &path, const pstring &libname)
: m_lib(nullptr)
{
	// FIXME: implement path search
	plib::unused_var(path);
	//  printf("win: loading <%s>\n", libname.c_str());
#ifdef _WIN32
	if (!libname.empty())
		m_lib = LoadLibrary(winapi_string(putf8string(libname)).c_str());
	else
		m_lib = GetModuleHandle(nullptr);
#elif defined(__EMSCRIPTEN__)
	//no-op
#else
	//printf("loading <%s>\n", libname.c_str());
	if (!libname.empty())
		m_lib = dlopen(putf8string(libname).c_str(), RTLD_LAZY);
	else
		m_lib = dlopen(nullptr, RTLD_LAZY);
#endif
	if (m_lib != nullptr)
		set_loaded(true);
	else
	{
		//printf("library <%s> not found!\n", libname.c_str());
	}
}

dynlib::~dynlib()
{
	if (m_lib != nullptr)
	{
#ifdef _WIN32
#else
		dlclose(m_lib);
		//printf("Closed %s\n", dlerror());
#endif
	}
}

void *dynlib::getsym_p(const pstring &name) const noexcept
{
#ifdef _WIN32
	return (void *) GetProcAddress((HMODULE) m_lib, putf8string(name).c_str());
#else
	return dlsym(m_lib, putf8string(name).c_str());
#endif
}

} // namespace plib