summaryrefslogtreecommitdiff
path: root/win32/lazyload.h
blob: a9fcff20959282e757fc98f9835a4e9236582aaa (plain)
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
#ifndef LAZYLOAD_H
#define LAZYLOAD_H

/* simplify loading of DLL functions */

struct proc_addr {
	FARPROC pfunction;
	unsigned initialized;
};

/* Declares a function to be loaded dynamically from a DLL. */
#define DECLARE_PROC_ADDR(rettype, function, ...) \
	static struct proc_addr proc_addr_##function = { NULL, 0 }; \
	rettype (WINAPI *function)(__VA_ARGS__)

/*
 * Loads a function from a DLL (once-only).
 * Returns non-NULL function pointer on success.
 * Returns NULL and sets errno == ENOSYS on failure.
 */
#define INIT_PROC_ADDR(dll, function) \
	(function = get_proc_addr(#dll, #function, &proc_addr_##function))

static inline void *get_proc_addr(const char *dll, const char *function, struct proc_addr *proc)
{
	/* only do this once */
	if (!proc->initialized) {
		HANDLE hnd = LoadLibraryExA(dll, NULL, LOAD_LIBRARY_SEARCH_SYSTEM32);
		if (hnd)
			proc->pfunction = GetProcAddress(hnd, function);
		proc->initialized = 1;
	}
	/* set ENOSYS if DLL or function was not found */
	if (!proc->pfunction)
		errno = ENOSYS;
	return proc->pfunction;
}

#endif