1#include "taichi/system/dynamic_loader.h"
2
3#ifdef WIN32
4#include "taichi/platform/windows/windows.h"
5#else
6#include <dlfcn.h>
7#endif
8
9namespace taichi {
10
11DynamicLoader::DynamicLoader(const std::string &dll_path) {
12 load_dll(dll_path);
13}
14
15void DynamicLoader::load_dll(const std::string &dll_path) {
16#ifdef WIN32
17 dll_ = (HMODULE)LoadLibraryA(dll_path.c_str());
18#else
19 dll_ = dlopen(dll_path.c_str(), RTLD_LAZY);
20#endif
21}
22
23void *DynamicLoader::load_function(const std::string &func_name) {
24 TI_ASSERT_INFO(loaded(), "DLL not opened");
25#ifdef WIN32
26 auto func = (void *)GetProcAddress((HMODULE)dll_, func_name.c_str());
27#else
28 auto func = dlsym(dll_, func_name.c_str());
29 const char *dlsym_error = dlerror();
30 TI_ERROR_IF(dlsym_error, "Cannot load function: {}", dlsym_error);
31#endif
32 TI_ERROR_IF(!func, "Function {} not found", func_name);
33 return func;
34}
35
36void DynamicLoader::close_dll() {
37 TI_ASSERT_INFO(loaded(), "DLL not opened");
38#ifdef WIN32
39 FreeLibrary((HMODULE)dll_);
40#else
41 dlclose(dll_);
42#endif
43 dll_ = nullptr;
44}
45
46DynamicLoader::~DynamicLoader() {
47 if (loaded())
48 close_dll();
49}
50
51bool DynamicLoader::loaded() const {
52 return dll_ != nullptr;
53}
54
55} // namespace taichi
56