blob: abf764afdffc83a99a35e2ec668ba1702944ed47 [file] [log] [blame]
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001/*
Wenzel Jakob8f4eb002015-10-15 18:13:33 +02002 pybind11/common.h -- Basic macros
Wenzel Jakob38bd7112015-07-05 20:05:44 +02003
Wenzel Jakob8cb6cb32016-04-17 20:21:41 +02004 Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
Wenzel Jakob38bd7112015-07-05 20:05:44 +02005
6 All rights reserved. Use of this source code is governed by a
7 BSD-style license that can be found in the LICENSE file.
8*/
9
Wenzel Jakobbd4a5292015-07-11 17:41:48 +020010#pragma once
Wenzel Jakob38bd7112015-07-05 20:05:44 +020011
12#if !defined(NAMESPACE_BEGIN)
Wenzel Jakob53b26542016-01-17 22:36:43 +010013# define NAMESPACE_BEGIN(name) namespace name {
Wenzel Jakob38bd7112015-07-05 20:05:44 +020014#endif
15#if !defined(NAMESPACE_END)
Wenzel Jakob53b26542016-01-17 22:36:43 +010016# define NAMESPACE_END(name) }
Wenzel Jakob38bd7112015-07-05 20:05:44 +020017#endif
18
Wenzel Jakobb1b71402015-10-18 16:48:30 +020019#if !defined(PYBIND11_EXPORT)
Wenzel Jakob53b26542016-01-17 22:36:43 +010020# if defined(WIN32) || defined(_WIN32)
21# define PYBIND11_EXPORT __declspec(dllexport)
22# else
23# define PYBIND11_EXPORT __attribute__ ((visibility("default")))
24# endif
Wenzel Jakob0fb85282015-10-19 23:50:51 +020025#endif
26
Wenzel Jakob53b26542016-01-17 22:36:43 +010027#if defined(_MSC_VER)
28# define PYBIND11_NOINLINE __declspec(noinline)
29#else
30# define PYBIND11_NOINLINE __attribute__ ((noinline))
31#endif
32
Wenzel Jakob1ae77fe2016-01-17 22:36:43 +010033#define PYBIND11_VERSION_MAJOR 1
Wenzel Jakobc4d7ccd2016-04-30 22:00:44 +020034#define PYBIND11_VERSION_MINOR 8
Wenzel Jakob1ae77fe2016-01-17 22:36:43 +010035
Wenzel Jakob53b26542016-01-17 22:36:43 +010036/// Include Python header, disable linking to pythonX_d.lib on Windows in debug mode
37#if defined(_MSC_VER)
38# define HAVE_ROUND
39# pragma warning(push)
40# pragma warning(disable: 4510 4610 4512 4005)
41# if _DEBUG
Wenzel Jakob8cb6cb32016-04-17 20:21:41 +020042# define PYBIND11_DEBUG_MARKER
Wenzel Jakob53b26542016-01-17 22:36:43 +010043# undef _DEBUG
44# endif
45#endif
46
47#include <Python.h>
48#include <frameobject.h>
Wenzel Jakob39e97e62016-04-25 03:26:15 +020049#include <pythread.h>
Wenzel Jakob53b26542016-01-17 22:36:43 +010050
51#ifdef isalnum
52# undef isalnum
53# undef isalpha
54# undef islower
55# undef isspace
56# undef isupper
57# undef tolower
58# undef toupper
59#endif
60
61#if defined(_MSC_VER)
Wenzel Jakob8cb6cb32016-04-17 20:21:41 +020062# if defined(PYBIND11_DEBUG_MARKER)
Wenzel Jakob53b26542016-01-17 22:36:43 +010063# define _DEBUG
Wenzel Jakob8cb6cb32016-04-17 20:21:41 +020064# undef PYBIND11_DEBUG_MARKER
65# endif
Wenzel Jakob53b26542016-01-17 22:36:43 +010066# pragma warning(pop)
67#endif
Wenzel Jakob38bd7112015-07-05 20:05:44 +020068
Wenzel Jakob38bd7112015-07-05 20:05:44 +020069#include <vector>
70#include <string>
71#include <stdexcept>
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +020072#include <unordered_set>
Wenzel Jakob38bd7112015-07-05 20:05:44 +020073#include <unordered_map>
Wenzel Jakob38bd7112015-07-05 20:05:44 +020074#include <memory>
Wenzel Jakobb6cf75d2016-01-29 11:39:32 +010075#include <typeindex>
Wenzel Jakob38bd7112015-07-05 20:05:44 +020076
Wenzel Jakob27e8e102016-01-17 22:36:37 +010077#if PY_MAJOR_VERSION >= 3 /// Compatibility macros for various Python versions
Wenzel Jakob48548ea2016-01-17 22:36:44 +010078#define PYBIND11_INSTANCE_METHOD_NEW(ptr, class_) PyInstanceMethod_New(ptr)
Wenzel Jakob27e8e102016-01-17 22:36:37 +010079#define PYBIND11_BYTES_CHECK PyBytes_Check
80#define PYBIND11_BYTES_FROM_STRING PyBytes_FromString
81#define PYBIND11_BYTES_FROM_STRING_AND_SIZE PyBytes_FromStringAndSize
82#define PYBIND11_BYTES_AS_STRING_AND_SIZE PyBytes_AsStringAndSize
83#define PYBIND11_BYTES_AS_STRING PyBytes_AsString
Wenzel Jakob5612a0c2016-05-01 00:32:18 +020084#define PYBIND11_BYTES_CHECK PyBytes_Check
Wenzel Jakob27e8e102016-01-17 22:36:37 +010085#define PYBIND11_LONG_CHECK(o) PyLong_Check(o)
86#define PYBIND11_LONG_AS_LONGLONG(o) PyLong_AsLongLong(o)
87#define PYBIND11_LONG_AS_UNSIGNED_LONGLONG(o) PyLong_AsUnsignedLongLong(o)
Wenzel Jakob56e9f492016-01-17 22:36:38 +010088#define PYBIND11_BYTES_NAME "bytes"
Wenzel Jakob27e8e102016-01-17 22:36:37 +010089#define PYBIND11_STRING_NAME "str"
90#define PYBIND11_SLICE_OBJECT PyObject
Wenzel Jakobd561cb02016-01-17 22:36:41 +010091#define PYBIND11_FROM_STRING PyUnicode_FromString
92#define PYBIND11_OB_TYPE(ht_type) (ht_type).ob_base.ob_base.ob_type
93#define PYBIND11_PLUGIN_IMPL(name) \
94 extern "C" PYBIND11_EXPORT PyObject *PyInit_##name()
Wenzel Jakob27e8e102016-01-17 22:36:37 +010095#else
Wenzel Jakob48548ea2016-01-17 22:36:44 +010096#define PYBIND11_INSTANCE_METHOD_NEW(ptr, class_) PyMethod_New(ptr, nullptr, class_)
Wenzel Jakob27e8e102016-01-17 22:36:37 +010097#define PYBIND11_BYTES_CHECK PyString_Check
98#define PYBIND11_BYTES_FROM_STRING PyString_FromString
99#define PYBIND11_BYTES_FROM_STRING_AND_SIZE PyString_FromStringAndSize
100#define PYBIND11_BYTES_AS_STRING_AND_SIZE PyString_AsStringAndSize
101#define PYBIND11_BYTES_AS_STRING PyString_AsString
Wenzel Jakob5612a0c2016-05-01 00:32:18 +0200102#define PYBIND11_BYTES_CHECK PyString_Check
Wenzel Jakob27e8e102016-01-17 22:36:37 +0100103#define PYBIND11_LONG_CHECK(o) (PyInt_Check(o) || PyLong_Check(o))
104#define PYBIND11_LONG_AS_LONGLONG(o) (PyInt_Check(o) ? (long long) PyLong_AsLong(o) : PyLong_AsLongLong(o))
105#define PYBIND11_LONG_AS_UNSIGNED_LONGLONG(o) (PyInt_Check(o) ? (unsigned long long) PyLong_AsUnsignedLong(o) : PyLong_AsUnsignedLongLong(o))
Wenzel Jakob56e9f492016-01-17 22:36:38 +0100106#define PYBIND11_BYTES_NAME "str"
Wenzel Jakob27e8e102016-01-17 22:36:37 +0100107#define PYBIND11_STRING_NAME "unicode"
108#define PYBIND11_SLICE_OBJECT PySliceObject
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100109#define PYBIND11_FROM_STRING PyString_FromString
110#define PYBIND11_OB_TYPE(ht_type) (ht_type).ob_type
111#define PYBIND11_PLUGIN_IMPL(name) \
112 extern "C" PYBIND11_EXPORT PyObject *init##name()
Wenzel Jakob27e8e102016-01-17 22:36:37 +0100113#endif
Wenzel Jakob57082212015-09-04 23:42:12 +0200114
Wenzel Jakobfbafdea2016-04-25 15:02:43 +0200115#if PY_VERSION_HEX >= 0x03050000 && PY_VERSION_HEX < 0x03050200
116extern "C" {
117 struct _Py_atomic_address { void *value; };
118 PyAPI_DATA(_Py_atomic_address) _PyThreadState_Current;
119};
120#endif
121
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100122#define PYBIND11_TRY_NEXT_OVERLOAD ((PyObject *) 1) // special failure return code
Wenzel Jakob77586fd2016-03-06 13:38:18 +0100123#define PYBIND11_STRINGIFY(x) #x
124#define PYBIND11_TOSTRING(x) PYBIND11_STRINGIFY(x)
125#define PYBIND11_INTERNALS_ID "__pybind11_" \
126 PYBIND11_TOSTRING(PYBIND11_VERSION_MAJOR) "_" PYBIND11_TOSTRING(PYBIND11_VERSION_MINOR) "__"
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100127
128#define PYBIND11_PLUGIN(name) \
129 static PyObject *pybind11_init(); \
130 PYBIND11_PLUGIN_IMPL(name) { \
131 try { \
132 return pybind11_init(); \
133 } catch (const std::exception &e) { \
134 PyErr_SetString(PyExc_ImportError, e.what()); \
135 return nullptr; \
136 } \
137 } \
138 PyObject *pybind11_init()
139
Wenzel Jakob8f4eb002015-10-15 18:13:33 +0200140NAMESPACE_BEGIN(pybind11)
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200141
142typedef Py_ssize_t ssize_t;
143
144/// Approach used to cast a previously unknown C++ instance into a Python object
145enum class return_value_policy : int {
Wenzel Jakobf7b58742016-04-25 23:04:27 +0200146 /** This is the default return value policy, which falls back to the policy
147 return_value_policy::take_ownership when the return value is a pointer.
148 Otherwise, it uses return_value::move or return_value::copy for rvalue
149 and lvalue references, respectively. See below for a description of what
150 all of these different policies do. */
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200151 automatic = 0,
Wenzel Jakob7d0162a2016-04-25 03:24:46 +0200152
Wenzel Jakobf7b58742016-04-25 23:04:27 +0200153 /** As above, but use policy return_value_policy::reference when the return
Wenzel Jakobe84f5572016-04-26 23:19:19 +0200154 value is a pointer. You probably won't need to use this. */
Wenzel Jakob8bd31c72016-04-14 14:26:13 +0200155 automatic_reference,
Wenzel Jakob7d0162a2016-04-25 03:24:46 +0200156
Wenzel Jakobf7b58742016-04-25 23:04:27 +0200157 /** Reference an existing object (i.e. do not create a new copy) and take
158 ownership. Python will call the destructor and delete operator when the
159 object’s reference count reaches zero. Undefined behavior ensues when
160 the C++ side does the same.. */
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200161 take_ownership,
Wenzel Jakob7d0162a2016-04-25 03:24:46 +0200162
Wenzel Jakobf7b58742016-04-25 23:04:27 +0200163 /** Create a new copy of the returned object, which will be owned by
164 Python. This policy is comparably safe because the lifetimes of the two
165 instances are decoupled. */
166 copy,
167
168 /** Use std::move to move the return value contents into a new instance
169 that will be owned by Python. This policy is comparably safe because the
170 lifetimes of the two instances (move source and destination) are
171 decoupled. */
172 move,
173
174 /** Reference an existing object, but do not take ownership. The C++ side
175 is responsible for managing the object’s lifetime and deallocating it
176 when it is no longer used. Warning: undefined behavior will ensue when
Wenzel Jakobe84f5572016-04-26 23:19:19 +0200177 the C++ side deletes an object that is still referenced and used by
178 Python. */
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200179 reference,
Wenzel Jakob7d0162a2016-04-25 03:24:46 +0200180
Wenzel Jakobe84f5572016-04-26 23:19:19 +0200181 /** This policy only applies to methods and properties. It references the
182 object without taking ownership similar to the above
183 return_value_policy::reference policy. In contrast to that policy, the
184 function or property’s implicit this argument (called the parent) is
185 considered to be the the owner of the return value (the child).
186 pybind11 then couples the lifetime of the parent to the child via a
187 reference relationship that ensures that the parent cannot be garbage
188 collected while Python is still using the child. More advanced
189 variations of this scheme are also possible using combinations of
190 return_value_policy::reference and the keep_alive call policy */
Wenzel Jakobf7b58742016-04-25 23:04:27 +0200191 reference_internal
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200192};
193
194/// Format strings for basic number types
195template <typename type> struct format_descriptor { };
Ben Pritchard2de6e1d2016-02-18 13:20:15 -0500196#define PYBIND11_DECL_FMT(t, n) template<> struct format_descriptor<t> { static std::string value() { return n; }; }
Wenzel Jakobb1b71402015-10-18 16:48:30 +0200197PYBIND11_DECL_FMT(int8_t, "b"); PYBIND11_DECL_FMT(uint8_t, "B"); PYBIND11_DECL_FMT(int16_t, "h"); PYBIND11_DECL_FMT(uint16_t, "H");
198PYBIND11_DECL_FMT(int32_t, "i"); PYBIND11_DECL_FMT(uint32_t, "I"); PYBIND11_DECL_FMT(int64_t, "q"); PYBIND11_DECL_FMT(uint64_t, "Q");
199PYBIND11_DECL_FMT(float, "f"); PYBIND11_DECL_FMT(double, "d"); PYBIND11_DECL_FMT(bool, "?");
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200200
201/// Information record describing a Python buffer object
202struct buffer_info {
Wenzel Jakobe45b2902016-01-17 22:36:41 +0100203 void *ptr; // Pointer to the underlying storage
204 size_t itemsize; // Size of individual items in bytes
205 size_t size; // Total number of entries
206 std::string format; // For homogeneous buffers, this should be set to format_descriptor<T>::value
207 int ndim; // Number of dimensions
208 std::vector<size_t> shape; // Shape of the tensor (1 entry per dimension)
209 std::vector<size_t> strides; // Number of entries between adjacent entries (for each per dimension)
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200210
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200211 buffer_info(void *ptr, size_t itemsize, const std::string &format, int ndim,
212 const std::vector<size_t> &shape, const std::vector<size_t> &strides)
Wenzel Jakobd33361a2016-01-17 22:36:40 +0100213 : ptr(ptr), itemsize(itemsize), size(1), format(format),
214 ndim(ndim), shape(shape), strides(strides) {
215 for (int i=0; i<ndim; ++i) size *= shape[i];
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200216 }
Wenzel Jakobd33361a2016-01-17 22:36:40 +0100217
218 buffer_info(Py_buffer *view)
219 : ptr(view->buf), itemsize(view->itemsize), size(1), format(view->format),
220 ndim(view->ndim), shape(view->ndim), strides(view->ndim), view(view) {
221 for (int i = 0; i < view->ndim; ++i) {
222 shape[i] = (size_t) view->shape[i];
223 strides[i] = (size_t) view->strides[i];
224 size *= shape[i];
225 }
226 }
227
228 ~buffer_info() {
229 if (view) { PyBuffer_Release(view); delete view; }
230 }
231private:
232 Py_buffer *view = nullptr;
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200233};
234
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200235NAMESPACE_BEGIN(detail)
236
Wenzel Jakob96c10532015-10-01 16:42:15 +0200237inline std::string error_string();
238
Wenzel Jakob88d1d042016-01-20 01:26:42 +0100239/// Core part of the 'instance' type which POD (needed to be able to use 'offsetof')
240template <typename type> struct instance_essentials {
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200241 PyObject_HEAD
242 type *value;
243 PyObject *parent;
Wenzel Jakob5f218b32016-01-17 22:36:39 +0100244 PyObject *weakrefs;
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200245 bool owned : 1;
246 bool constructed : 1;
Wenzel Jakob88d1d042016-01-20 01:26:42 +0100247};
248
249/// PyObject wrapper around generic types, includes a special holder type that is responsible for lifetime management
250template <typename type, typename holder_type = std::unique_ptr<type>> struct instance : instance_essentials<type> {
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200251 holder_type holder;
252};
253
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +0200254struct overload_hash {
255 inline std::size_t operator()(const std::pair<const PyObject *, const char *>& v) const {
256 size_t value = std::hash<const void *>()(v.first);
257 value ^= std::hash<const void *>()(v.second) + 0x9e3779b9 + (value<<6) + (value>>2);
258 return value;
259 }
260};
261
Wenzel Jakob43398a82015-07-28 16:12:20 +0200262/// Internal data struture used to track registered instances and types
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200263struct internals {
Wenzel Jakobb6cf75d2016-01-29 11:39:32 +0100264 std::unordered_map<std::type_index, void*> registered_types_cpp; // std::type_index -> type_info
265 std::unordered_map<const void *, void*> registered_types_py; // PyTypeObject* -> type_info
266 std::unordered_map<const void *, void*> registered_instances; // void * -> PyObject*
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +0200267 std::unordered_set<std::pair<const PyObject *, const char *>, overload_hash> inactive_overload_cache;
Wenzel Jakob39e97e62016-04-25 03:26:15 +0200268#if defined(WITH_THREAD)
269 int tstate = 0;
270 PyInterpreterState *istate = nullptr;
271#endif
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200272};
273
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200274/// Return a reference to the current 'internals' information
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200275inline internals &get_internals();
276
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200277/// Index sequence for convenient template metaprogramming involving tuples
278template<size_t ...> struct index_sequence { };
279template<size_t N, size_t ...S> struct make_index_sequence : make_index_sequence <N - 1, N - 1, S...> { };
280template<size_t ...S> struct make_index_sequence <0, S...> { typedef index_sequence<S...> type; };
281
282/// Strip the class from a method type
Wenzel Jakobad696342016-05-03 13:28:40 +0200283template <typename T> struct remove_class { };
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200284template <typename C, typename R, typename... A> struct remove_class<R (C::*)(A...)> { typedef R type(A...); };
285template <typename C, typename R, typename... A> struct remove_class<R (C::*)(A...) const> { typedef R type(A...); };
286
287/// Helper template to strip away type modifiers
Wenzel Jakob4177ed42016-01-17 22:36:38 +0100288template <typename T> struct intrinsic_type { typedef T type; };
289template <typename T> struct intrinsic_type<const T> { typedef typename intrinsic_type<T>::type type; };
290template <typename T> struct intrinsic_type<T*> { typedef typename intrinsic_type<T>::type type; };
291template <typename T> struct intrinsic_type<T&> { typedef typename intrinsic_type<T>::type type; };
292template <typename T> struct intrinsic_type<T&&> { typedef typename intrinsic_type<T>::type type; };
293template <typename T, size_t N> struct intrinsic_type<const T[N]> { typedef typename intrinsic_type<T>::type type; };
294template <typename T, size_t N> struct intrinsic_type<T[N]> { typedef typename intrinsic_type<T>::type type; };
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200295
296/// Helper type to replace 'void' in some expressions
297struct void_type { };
Wenzel Jakob281aa0e2015-07-30 15:29:00 +0200298
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +0200299/// to_string variant which also accepts strings
300template <typename T> inline typename std::enable_if<!std::is_enum<T>::value, std::string>::type
301to_string(const T &value) { return std::to_string(value); }
302template <> inline std::string to_string(const std::string &value) { return value; }
303template <typename T> inline typename std::enable_if<std::is_enum<T>::value, std::string>::type
304to_string(T value) { return std::to_string((int) value); }
305
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200306NAMESPACE_END(detail)
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +0200307
Wenzel Jakobad696342016-05-03 13:28:40 +0200308#define PYBIND11_RUNTIME_EXCEPTION(name) \
309 class name : public std::runtime_error { public: \
310 name(const std::string &w) : std::runtime_error(w) { }; \
311 name(const char *s) : std::runtime_error(s) { }; \
312 name() : std::runtime_error("") { } \
313 };
314
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +0200315// C++ bindings of core Python exceptions
Wenzel Jakobad696342016-05-03 13:28:40 +0200316class error_already_set : public std::runtime_error { public: error_already_set() : std::runtime_error(detail::error_string()) {} };
317PYBIND11_RUNTIME_EXCEPTION(stop_iteration)
318PYBIND11_RUNTIME_EXCEPTION(index_error)
319PYBIND11_RUNTIME_EXCEPTION(cast_error) /// Thrown when pybind11::cast or handle::call fail due to a type casting error
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +0200320
Wenzel Jakobfc92d822016-04-30 23:55:44 +0200321[[noreturn]] PYBIND11_NOINLINE inline void pybind11_fail(const char *reason) { throw std::runtime_error(reason); }
322[[noreturn]] PYBIND11_NOINLINE inline void pybind11_fail(const std::string &reason) { throw std::runtime_error(reason); }
Wenzel Jakob678d7872016-01-17 22:36:41 +0100323
Wenzel Jakob8f4eb002015-10-15 18:13:33 +0200324NAMESPACE_END(pybind11)