-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmain.cpp
95 lines (70 loc) · 2.03 KB
/
main.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 <stdio.h>
#include <dlfcn.h>
#include "polygon.hpp"
#include "external_test.cpp"
#define BUILDING_DLL
//-fvisibility-inlines-hidden
//-fvisibility=hidden
void* load_library(const char* library_so_path)
{
// load the triangle library
void* dll_ptr = dlopen("./triangle.so", RTLD_LAZY);
if (dll_ptr == NULL)
{
printf("ERROR: load_dynamic_library, cannot load library %s, error= %s \n",
library_so_path, dlerror() );
//cerr << "Cannot load library: " << dlerror() << '\n';
return NULL;
}
// reset errors
dlerror();
return dll_ptr;
}
void* load_symbol(void* loaded_library, const char* symbol_name)
{
dlerror(); // reset errors
void* symbol_ptr = dlsym(loaded_library, symbol_name);
const char *dlsym_error = dlerror();
if (dlsym_error)
{
printf("ERROR: load_symbol, cannot load symbol %s, error= %s \n",
symbol_name, dlsym_error);
dlclose(loaded_library);
return NULL;
}
return symbol_ptr;
}
int main() {
//using std::cout;
//using std::cerr;
printf("test_var= %d\n", test_var);
test_var = 5;
void* loaded_dll = load_library("./triangle.so");
{
// load the symbol (Hello Function)
printf("Loading symbol hello...\n");
typedef void (*hello_t)();
dlerror(); // reset errors
hello_t hello = (hello_t) load_symbol(loaded_dll, "hello");
// call the loaded function
printf("Calling hello...\n");
hello();
}
{
// load the symbols (class; creation/deletion and stuff)
printf("Loading class symbols\n");
create_t* create_triangle = (create_t*) load_symbol(loaded_dll, "create");
destroy_t* destroy_triangle = (destroy_t*) load_symbol(loaded_dll, "destroy");
if(create_triangle == NULL || destroy_triangle == NULL)
return 1;
// create an instance of the class
class polygon* poly = create_triangle();
// use the class
poly->set_side_length(7);
printf("class_test: the area is %f \n", poly->area() );
// destroy the class
destroy_triangle(poly);
}
// unload the triangle library
dlclose(loaded_dll);
}