-
Notifications
You must be signed in to change notification settings - Fork 34
/
main.c
71 lines (66 loc) · 1.65 KB
/
main.c
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
#define _BSD_SOURCE // usleep()
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <dlfcn.h>
#include "game.h"
const char *GAME_LIBRARY = "./libgame.so";
struct game {
void *handle;
ino_t id;
struct game_api api;
struct game_state *state;
};
static void game_load(struct game *game)
{
struct stat attr;
if ((stat(GAME_LIBRARY, &attr) == 0) && (game->id != attr.st_ino)) {
if (game->handle) {
game->api.unload(game->state);
dlclose(game->handle);
}
void *handle = dlopen(GAME_LIBRARY, RTLD_NOW);
if (handle) {
game->handle = handle;
game->id = attr.st_ino;
const struct game_api *api = dlsym(game->handle, "GAME_API");
if (api != NULL) {
game->api = *api;
if (game->state == NULL)
game->state = game->api.init();
game->api.reload(game->state);
} else {
dlclose(game->handle);
game->handle = NULL;
game->id = 0;
}
} else {
game->handle = NULL;
game->id = 0;
}
}
}
void game_unload(struct game *game)
{
if (game->handle) {
game->api.finalize(game->state);
game->state = NULL;
dlclose(game->handle);
game->handle = NULL;
game->id = 0;
}
}
int main(void)
{
struct game game = {0};
for (;;) {
game_load(&game);
if (game.handle)
if (!game.api.step(game.state))
break;
usleep(100000);
}
game_unload(&game);
return 0;
}