summaryrefslogtreecommitdiffhomepage
path: root/src/vcall.h
blob: caee70afa1063bd421bd75d402b006a90a02912a (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
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
/*
 * Copyright © 2022 Michael Smith <mikesmiffy128@gmail.com>
 *
 * Permission to use, copy, modify, and/or distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED “AS IS” AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
 * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
 * AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
 * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
 * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
 * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 * PERFORMANCE OF THIS SOFTWARE.
 */

#ifndef INC_VCALL_H
#define INC_VCALL_H

#include "gamedata.h"

/*
 * Convenient facilities for calling simple (single-table) virtual functions on
 * possibly-opaque pointers to C++ objects.
 */

#ifdef _WIN32
#if defined(__GNUC__) || defined(__clang__)
#define VCALLCONV __thiscall
#else
// XXX: could support MSVC via __fastcall and dummy param, but is there a point?
#error C __thiscall support requires Clang or GCC
#endif
#else
#define VCALLCONV
#endif

#define _DECL_VFUNC_DYN(ret, conv, name, ...) \
	/* XXX: GCC extension, seems worthwhile vs having two macros for one thing.
	   Replace with __VA_OPT__(,) whenever that gets fully standardised. */ \
	typedef ret (*conv name##_func)(void *this, ##__VA_ARGS__);
#define _DECL_VFUNC(ret, conv, name, idx, ...) \
	enum { vtidx_##name = (idx) }; \
	_DECL_VFUNC_DYN(ret, conv, name, ##__VA_ARGS__)

/* Define a virtual function with a known index */
#define DECL_VFUNC(ret, name, idx, ...) \
	_DECL_VFUNC(ret, VCALLCONV, name, idx, ##__VA_ARGS__)

/* Define a virtual function with a known index, without thiscall convention */
#define DECL_VFUNC_CDECL(ret, name, idx, ...) \
	_DECL_VFUNC(ret, , name, idx, ##__VA_ARGS__)

/* Define a virtual function with an index defined elsewhere */
#define DECL_VFUNC_DYN(ret, name, ...) \
	_DECL_VFUNC_DYN(ret, VCALLCONV, name, ##__VA_ARGS__)

/* Define a virtual function with an index defined elsewhere, without thiscall */
#define DECL_VFUNC_CDECLDYN(ret, name, ...) \
	_DECL_VFUNC_DYN(ret, , name, ##__VA_ARGS__)

#define VFUNC(x, name) ((*(name##_func **)(x))[vtidx_##name])
#define VCALL(x, name, ...) VFUNC(x, name)(x, ##__VA_ARGS__)

#endif

// vi: sw=4 ts=4 noet tw=80 cc=80