-
Notifications
You must be signed in to change notification settings - Fork 37
Expand file tree
/
Copy pathwrap_macros.h
More file actions
executable file
·371 lines (321 loc) · 13.4 KB
/
wrap_macros.h
File metadata and controls
executable file
·371 lines (321 loc) · 13.4 KB
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
/**
* =============================================================================
* Source Python
* Copyright (C) 2012-2015 Source Python Development Team. All rights reserved.
* =============================================================================
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3.0, as published by the
* Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, the Source Python Team gives you permission
* to link the code of this program (as well as its derivative works) to
* "Half-Life 2," the "Source Engine," and any Game MODs that run on software
* by the Valve Corporation. You must obey the GNU General Public License in
* all respects for all other code used. Additionally, the Source.Python
* Development Team grants this exception to all derivative works.
*/
#ifndef _WRAP_MACROS_H
#define _WRAP_MACROS_H
//---------------------------------------------------------------------------------
// Includes
//---------------------------------------------------------------------------------
#include "boost/function.hpp"
#include "boost/function_types/parameter_types.hpp"
#include "boost/python.hpp"
using namespace boost::python;
#include "modules/core/core_cache.h"
//---------------------------------------------------------------------------------
// Define checks
//---------------------------------------------------------------------------------
#if !defined(SOURCE_ENGINE)
#error("SOURCE_ENGINE define must be globally defined, did we forget?");
#elif !defined(SOURCE_ENGINE_BRANCH)
#error("SOURCE_ENGINE_BRANCH define must be globally defined, did we forget?");
#endif
//---------------------------------------------------------------------------------
// Macros to expose function typedefs
//---------------------------------------------------------------------------------
template<class Function>
inline void* GetFuncPtr(Function func)
{
return (void*) func.functor.members.func_ptr;
}
// Example typedef:
// typedef int (*MultiplyFn)(int, int);
//
// Example usage:
// BOOST_FUNCTION_TYPEDEF(int (int, int), BoostMultiplyFn)
#define BOOST_FUNCTION_TYPEDEF(sig, cpp_name) \
typedef boost::function< sig> cpp_name;
// Example usage:
// EXPOSE_FUNCTION_TYPEDEF(BoostMultiplyFn, "MultiplyFn")
#define EXPOSE_FUNCTION_TYPEDEF(cpp_name, py_name) \
class_<cpp_name>(py_name, no_init) \
.def("__call__", &cpp_name::operator()) \
.def(GET_PTR_NAME, &GetFuncPtr<cpp_name>, return_by_value_policy()) \
;
#define EXPOSE_FUNCTION_TYPEDEF_RET(cpp_name, py_name, policy) \
class_<cpp_name>(py_name, no_init) \
.def("__call__", &cpp_name::operator(), policy) \
.def(GET_PTR_NAME, &GetFuncPtr<cpp_name>, return_by_value_policy()) \
;
//---------------------------------------------------------------------------------
// Surround boost python statements with this macro in order to handle exceptions.
//---------------------------------------------------------------------------------
#define BEGIN_BOOST_PY() \
try {
#define END_BOOST_PY( ... ) \
} catch( ... ) { \
PyErr_Print(); \
PyErr_Clear(); \
return __VA_ARGS__; \
}
#define END_BOOST_PY_NORET( ... ) \
} catch( ... ) { \
PyErr_Print(); \
PyErr_Clear(); \
}
//---------------------------------------------------------------------------------
// Use this macro to raise a Python exception.
//---------------------------------------------------------------------------------
#define BOOST_RAISE_EXCEPTION( exceptionName, exceptionString, ... ) \
{ \
PyErr_Format(exceptionName, exceptionString, ##__VA_ARGS__); \
throw_error_already_set(); \
}
//---------------------------------------------------------------------------------
// This macro will turn input into a string.
//---------------------------------------------------------------------------------
#define XSTRINGIFY(s) STRINGIFY(s)
#define STRINGIFY(s) #s
//---------------------------------------------------------------------------------
// This macro returns the given overloaded method
//---------------------------------------------------------------------------------
#define GET_METHOD(return_type, class_name, method, ...) \
static_cast< return_type (class_name::*)( __VA_ARGS__ ) >(&class_name::method)
#define GET_CONST_METHOD(return_type, class_name, method, ...) \
static_cast< return_type (class_name::*)( __VA_ARGS__ ) const >(&class_name::method)
//---------------------------------------------------------------------------------
// This macro returns the given overloaded function
//---------------------------------------------------------------------------------
#define GET_FUNCTION(return_type, function, ...) \
static_cast< return_type(*)( __VA_ARGS__ ) >(&function)
//---------------------------------------------------------------------------------
// Use this to transfer ownership of a pointer to Python.
//---------------------------------------------------------------------------------
template <typename T>
object transfer_ownership_to_python(T *pPtr)
{
typename manage_new_object::apply<T*>::type holder;
return object(handle<>(holder(*pPtr)));
};
//---------------------------------------------------------------------------------
// Use these to declare classmethod wrappers.
//---------------------------------------------------------------------------------
#define CLASSMETHOD(cls, name, ...) \
classmethod(cls.def(name, __VA_ARGS__), name)
template<typename T>
T classmethod(T cls, const char *szName)
{
PyTypeObject *type = downcast<PyTypeObject>(cls.ptr());
PyDict_SetItemString(
type->tp_dict, szName,
PyClassMethod_New(PyDict_GetItemString(type->tp_dict, szName))
);
return cls;
};
//---------------------------------------------------------------------------------
// Use these to declare cached properties.
//---------------------------------------------------------------------------------
#define CACHED_PROPERTY(cls, name, ...) \
cached_property(cls.add_property(name, __VA_ARGS__), name)
template<typename T>
T cached_property(T cls, const char *szName)
{
cls.attr(szName) = transfer_ownership_to_python(
CCachedProperty::wrap_descriptor(cls.attr(szName), cls, szName)
);
return cls;
};
//---------------------------------------------------------------------------------
// Use this template to create variadic class methods
//---------------------------------------------------------------------------------
struct raw_method_dispatcher
{
public:
raw_method_dispatcher(object func):
func(func)
{
}
PyObject *operator()(PyObject *args, PyObject *kwargs)
{
return incref(
object(
func(
object(object(boost::python::detail::borrowed_reference(args))[0]),
object(
boost::python::tuple(
boost::python::detail::borrowed_reference(args)
).slice(1, _)
),
kwargs ? dict(boost::python::detail::borrowed_reference(kwargs)) : dict()
)
).ptr()
);
}
private:
object func;
};
template<class T>
object raw_method(T func, int min_args = 0)
{
return boost::python::detail::make_raw_function(
objects::py_function(
raw_method_dispatcher(make_function(func)),
boost::mpl::vector1<PyObject *>(),
min_args + 1,
(std::numeric_limits<unsigned>::max)()
)
);
}
template<class T, typename U>
struct very_raw_method_dispatcher
{
public:
very_raw_method_dispatcher(T func):
func(func)
{
}
PyObject *operator()(PyObject *args, PyObject *kwargs)
{
return incref((extract<U &>(PyTuple_GET_ITEM(args, 0))().*func)(args, kwargs).ptr());
}
private:
T func;
};
template<class T>
object very_raw_method(T func, int min_args = 0)
{
return boost::python::detail::make_raw_function(
objects::py_function(
very_raw_method_dispatcher<
T, typename boost::mpl::at_c<boost::function_types::parameter_types<T>, 0>::type
>(func),
boost::mpl::vector1<PyObject *>(),
min_args + 1,
(std::numeric_limits<unsigned>::max)()
)
);
}
//---------------------------------------------------------------------------------
// Use this macro to define a function or class method that raises a
// NotImplementedError. This is quite hacky, but saves a lot work!
//---------------------------------------------------------------------------------
inline object _NotImplementedOnThisEngine(boost::python::tuple args, boost::python::dict kw)
{
BOOST_RAISE_EXCEPTION(PyExc_NotImplementedError, "Not implemented on this engine.");
return object();
}
#define NOT_IMPLEMENTED(name) \
def(name, raw_function(&_NotImplementedOnThisEngine), "Not implemented on this engine.")
#define NOT_IMPLEMENTED_ATTR(name) \
add_property(name, raw_function(&_NotImplementedOnThisEngine), raw_function(&_NotImplementedOnThisEngine), "Not implemented on this engine.")
//---------------------------------------------------------------------------------
// Use this macro to default a not implemented value to None.
//---------------------------------------------------------------------------------
#define NOT_IMPLEMENTED_VALUE(classname, name) \
PyDict_SetItemString( \
converter::registry::query(typeid(classname))->m_class_object->tp_dict, \
name, \
object().ptr() \
);
//---------------------------------------------------------------------------------
// Use this macro to check the return value of a get_override(...) call.
//---------------------------------------------------------------------------------
#define CHECK_OVERRIDE(override) \
if (override.is_none()) \
BOOST_RAISE_EXCEPTION(PyExc_NotImplementedError, "Method must be implemented by a subclass.")
//---------------------------------------------------------------------------------
// Use this macro to add a specialization for a class to hold back-references.
//---------------------------------------------------------------------------------
#define BOOST_SPECIALIZE_HAS_BACK_REFERENCE( classname ) \
namespace boost { namespace python { \
template<> \
struct has_back_reference<classname> : mpl::true_ \
{}; \
}}
//---------------------------------------------------------------------------------
// These macros allow us to include engine / branch specific files
//---------------------------------------------------------------------------------
// Current working directory macros
#define JOIN_PATH(folder, file_path) XSTRINGIFY(folder/file_path)
#define ENGINE_INCLUDE_PATH(file_path) JOIN_PATH(SOURCE_ENGINE, file_path)
#define ENGINE_BRANCH_INCLUDE_PATH(file_path) JOIN_PATH(SOURCE_ENGINE_BRANCH, file_path)
//---------------------------------------------------------------------------------
// These typedefs save some typing. Use this policy for any functions that return
// a newly allocated instance of a class which you need to delete yourself.
//---------------------------------------------------------------------------------
typedef return_value_policy<manage_new_object> manage_new_object_policy;
//---------------------------------------------------------------------------------
// Use this policy for objects that someone else will free.
//---------------------------------------------------------------------------------
typedef return_value_policy<reference_existing_object> reference_existing_object_policy;
//---------------------------------------------------------------------------------
// Use this policy for functions that return const objects.
//---------------------------------------------------------------------------------
typedef return_value_policy<copy_const_reference> copy_const_reference_policy;
typedef return_value_policy<return_by_value> return_by_value_policy;
//---------------------------------------------------------------------------------
// Call policies that initializes the wrapper hierarchy.
//---------------------------------------------------------------------------------
template<typename HeldType, typename BasePolicies = default_call_policies, int iSelf = -1>
struct initialize_wrapper_policies : BasePolicies
{
template<typename ArgumentPackage>
static PyObject *postcall(const ArgumentPackage &args, PyObject *pResult)
{
PyObject *pSelf = boost::python::detail::get(boost::mpl::int_<iSelf>(), args);
boost::python::detail::initialize_wrapper(
pSelf,
get_pointer((HeldType)extract<HeldType>(pSelf))
);
return BasePolicies::postcall(args, pResult);
}
};
//---------------------------------------------------------------------------------
// Provides post-construction initialization support of the Python instances.
//---------------------------------------------------------------------------------
template<typename BasePolicies = default_call_policies, int iSelf = -1>
struct post_constructor_policies : BasePolicies
{
public:
post_constructor_policies(object initializer):
m_initializer(initializer)
{
}
template<typename ArgumentPackage>
PyObject *postcall(const ArgumentPackage &args, PyObject *pResult)
{
BasePolicies::postcall(args, pResult);
m_initializer(
*(boost::python::make_tuple(
object(handle<>(incref(boost::python::detail::get(boost::mpl::int_<iSelf>(), args))))) +
boost::python::tuple(handle<>(args.base))
)
);
decref(pResult);
return incref(Py_None); // __init__ should always return None
}
private:
object m_initializer;
};
#endif // _WRAP_MACROS_H