blob: f00f16ba8811b29f90d045552f8824116b496dc8 [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
4 Copyright (c) 2015 Wenzel Jakob <wenzel@inf.ethz.ch>
5
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)
13#define NAMESPACE_BEGIN(name) namespace name {
14#endif
15#if !defined(NAMESPACE_END)
16#define NAMESPACE_END(name) }
17#endif
18
Wenzel Jakobb1b71402015-10-18 16:48:30 +020019#if !defined(PYBIND11_EXPORT)
Wenzel Jakob6c698fe2015-10-01 16:47:21 +020020#if defined(WIN32) || defined(_WIN32)
Wenzel Jakobb1b71402015-10-18 16:48:30 +020021#define PYBIND11_EXPORT __declspec(dllexport)
Wenzel Jakob38bd7112015-07-05 20:05:44 +020022#else
Wenzel Jakobb1b71402015-10-18 16:48:30 +020023#define PYBIND11_EXPORT __attribute__ ((visibility("default")))
Wenzel Jakob38bd7112015-07-05 20:05:44 +020024#endif
25#endif
Wenzel Jakob0fb85282015-10-19 23:50:51 +020026#if defined(_MSC_VER)
27#define PYBIND11_NOINLINE __declspec(noinline)
28#else
29#define PYBIND11_NOINLINE __attribute__ ((noinline))
30#endif
31
Wenzel Jakob38bd7112015-07-05 20:05:44 +020032
Wenzel Jakob38bd7112015-07-05 20:05:44 +020033#include <vector>
34#include <string>
35#include <stdexcept>
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +020036#include <unordered_set>
Wenzel Jakob38bd7112015-07-05 20:05:44 +020037#include <unordered_map>
Wenzel Jakob38bd7112015-07-05 20:05:44 +020038#include <memory>
39
40/// Include Python header, disable linking to pythonX_d.lib on Windows in debug mode
41#if defined(_MSC_VER)
42#define HAVE_ROUND
43#pragma warning(push)
Wenzel Jakob57082212015-09-04 23:42:12 +020044#pragma warning(disable: 4510 4610 4512 4005)
Wenzel Jakob38bd7112015-07-05 20:05:44 +020045#if _DEBUG
46#define _DEBUG_MARKER
47#undef _DEBUG
48#endif
49#endif
50#include <Python.h>
Wenzel Jakob96c10532015-10-01 16:42:15 +020051#include <frameobject.h>
Wenzel Jakob281aa0e2015-07-30 15:29:00 +020052#ifdef isalnum
53#undef isalnum
54#undef isalpha
55#undef islower
56#undef isspace
57#undef isupper
58#undef tolower
59#undef toupper
60#endif
Wenzel Jakob38bd7112015-07-05 20:05:44 +020061#if defined(_MSC_VER)
62#if defined(_DEBUG_MARKER)
63#define _DEBUG
64#undef _DEBUG_MARKER
65#endif
66#pragma warning(pop)
67#endif
68
Wenzel Jakob57082212015-09-04 23:42:12 +020069#if PY_MAJOR_VERSION >= 3
Wenzel Jakobdd57a342015-12-26 14:04:52 +010070#define PYBIND11_PLUGIN_IMPL(name) \
Wenzel Jakobb1b71402015-10-18 16:48:30 +020071 extern "C" PYBIND11_EXPORT PyObject *PyInit_##name()
Wenzel Jakob57082212015-09-04 23:42:12 +020072#else
Wenzel Jakobdd57a342015-12-26 14:04:52 +010073#define PYBIND11_PLUGIN_IMPL(name) \
Wenzel Jakobb1b71402015-10-18 16:48:30 +020074 extern "C" PYBIND11_EXPORT PyObject *init##name()
Wenzel Jakob57082212015-09-04 23:42:12 +020075#endif
Wenzel Jakobdd57a342015-12-26 14:04:52 +010076#define PYBIND11_PLUGIN(name) \
77 static PyObject *pybind11_init(); \
78 PYBIND11_PLUGIN_IMPL(name) { \
79 try { \
80 return pybind11_init(); \
81 } catch (const std::exception &e) { \
82 PyErr_SetString(PyExc_ImportError, e.what()); \
83 return nullptr; \
84 } \
85 } \
86 PyObject *pybind11_init()
87
Wenzel Jakob27e8e102016-01-17 22:36:37 +010088#if PY_MAJOR_VERSION >= 3 /// Compatibility macros for various Python versions
89#define PYBIND11_BYTES_CHECK PyBytes_Check
90#define PYBIND11_BYTES_FROM_STRING PyBytes_FromString
91#define PYBIND11_BYTES_FROM_STRING_AND_SIZE PyBytes_FromStringAndSize
92#define PYBIND11_BYTES_AS_STRING_AND_SIZE PyBytes_AsStringAndSize
93#define PYBIND11_BYTES_AS_STRING PyBytes_AsString
94#define PYBIND11_LONG_CHECK(o) PyLong_Check(o)
95#define PYBIND11_LONG_AS_LONGLONG(o) PyLong_AsLongLong(o)
96#define PYBIND11_LONG_AS_UNSIGNED_LONGLONG(o) PyLong_AsUnsignedLongLong(o)
Wenzel Jakob56e9f492016-01-17 22:36:38 +010097#define PYBIND11_BYTES_NAME "bytes"
Wenzel Jakob27e8e102016-01-17 22:36:37 +010098#define PYBIND11_STRING_NAME "str"
99#define PYBIND11_SLICE_OBJECT PyObject
100#else
101#define PYBIND11_BYTES_CHECK PyString_Check
102#define PYBIND11_BYTES_FROM_STRING PyString_FromString
103#define PYBIND11_BYTES_FROM_STRING_AND_SIZE PyString_FromStringAndSize
104#define PYBIND11_BYTES_AS_STRING_AND_SIZE PyString_AsStringAndSize
105#define PYBIND11_BYTES_AS_STRING PyString_AsString
106#define PYBIND11_LONG_CHECK(o) (PyInt_Check(o) || PyLong_Check(o))
107#define PYBIND11_LONG_AS_LONGLONG(o) (PyInt_Check(o) ? (long long) PyLong_AsLong(o) : PyLong_AsLongLong(o))
108#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 +0100109#define PYBIND11_BYTES_NAME "str"
Wenzel Jakob27e8e102016-01-17 22:36:37 +0100110#define PYBIND11_STRING_NAME "unicode"
111#define PYBIND11_SLICE_OBJECT PySliceObject
112#endif
Wenzel Jakob57082212015-09-04 23:42:12 +0200113
Wenzel Jakob8f4eb002015-10-15 18:13:33 +0200114NAMESPACE_BEGIN(pybind11)
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200115
116typedef Py_ssize_t ssize_t;
117
118/// Approach used to cast a previously unknown C++ instance into a Python object
119enum class return_value_policy : int {
120 /** Automatic: copy objects returned as values and take ownership of objects
121 returned as pointers */
122 automatic = 0,
123 /** Reference the object and take ownership. Python will call the
124 destructor and delete operator when the reference count reaches zero */
125 take_ownership,
126 /** Reference the object, but do not take ownership (dangerous when C++ code
127 deletes it and Python still has a nonzero reference count) */
128 reference,
129 /** Reference the object, but do not take ownership. The object is considered
130 be owned by the C++ instance whose method or property returned it. The
131 Python object will increase the reference count of this 'parent' by 1 */
132 reference_internal,
133 /// Create a new copy of the returned object, which will be owned by Python
134 copy
135};
136
137/// Format strings for basic number types
138template <typename type> struct format_descriptor { };
Wenzel Jakobb1b71402015-10-18 16:48:30 +0200139#define PYBIND11_DECL_FMT(t, n) template<> struct format_descriptor<t> { static std::string value() { return n; }; };
140PYBIND11_DECL_FMT(int8_t, "b"); PYBIND11_DECL_FMT(uint8_t, "B"); PYBIND11_DECL_FMT(int16_t, "h"); PYBIND11_DECL_FMT(uint16_t, "H");
141PYBIND11_DECL_FMT(int32_t, "i"); PYBIND11_DECL_FMT(uint32_t, "I"); PYBIND11_DECL_FMT(int64_t, "q"); PYBIND11_DECL_FMT(uint64_t, "Q");
142PYBIND11_DECL_FMT(float, "f"); PYBIND11_DECL_FMT(double, "d"); PYBIND11_DECL_FMT(bool, "?");
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200143
144/// Information record describing a Python buffer object
145struct buffer_info {
146 void *ptr;
Wenzel Jakobd33361a2016-01-17 22:36:40 +0100147 size_t itemsize, size;
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200148 std::string format; // for dense contents, this should be set to format_descriptor<T>::value
149 int ndim;
150 std::vector<size_t> shape;
151 std::vector<size_t> strides;
152
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200153 buffer_info(void *ptr, size_t itemsize, const std::string &format, int ndim,
154 const std::vector<size_t> &shape, const std::vector<size_t> &strides)
Wenzel Jakobd33361a2016-01-17 22:36:40 +0100155 : ptr(ptr), itemsize(itemsize), size(1), format(format),
156 ndim(ndim), shape(shape), strides(strides) {
157 for (int i=0; i<ndim; ++i) size *= shape[i];
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200158 }
Wenzel Jakobd33361a2016-01-17 22:36:40 +0100159
160 buffer_info(Py_buffer *view)
161 : ptr(view->buf), itemsize(view->itemsize), size(1), format(view->format),
162 ndim(view->ndim), shape(view->ndim), strides(view->ndim), view(view) {
163 for (int i = 0; i < view->ndim; ++i) {
164 shape[i] = (size_t) view->shape[i];
165 strides[i] = (size_t) view->strides[i];
166 size *= shape[i];
167 }
168 }
169
170 ~buffer_info() {
171 if (view) { PyBuffer_Release(view); delete view; }
172 }
173private:
174 Py_buffer *view = nullptr;
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200175};
176
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200177NAMESPACE_BEGIN(detail)
178
Wenzel Jakob96c10532015-10-01 16:42:15 +0200179inline std::string error_string();
180
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200181/// PyObject wrapper around generic types
182template <typename type, typename holder_type = std::unique_ptr<type>> struct instance {
183 PyObject_HEAD
184 type *value;
185 PyObject *parent;
Wenzel Jakob5f218b32016-01-17 22:36:39 +0100186 PyObject *weakrefs;
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200187 bool owned : 1;
188 bool constructed : 1;
189 holder_type holder;
190};
191
Wenzel Jakobfa1bfb22015-10-22 16:03:44 +0200192/// Additional type information which does not fit into the PyTypeObject
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200193struct type_info {
194 PyTypeObject *type;
195 size_t type_size;
Wenzel Jakobb2c2c792016-01-17 22:36:40 +0100196 void (*init_holder)(PyObject *, const void *);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200197 std::vector<PyObject *(*)(PyObject *, PyTypeObject *)> implicit_conversions;
Wenzel Jakob43398a82015-07-28 16:12:20 +0200198 buffer_info *(*get_buffer)(PyObject *, void *) = nullptr;
199 void *get_buffer_data = nullptr;
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200200};
201
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +0200202struct overload_hash {
203 inline std::size_t operator()(const std::pair<const PyObject *, const char *>& v) const {
204 size_t value = std::hash<const void *>()(v.first);
205 value ^= std::hash<const void *>()(v.second) + 0x9e3779b9 + (value<<6) + (value>>2);
206 return value;
207 }
208};
209
Wenzel Jakob2ac50442016-01-17 22:36:35 +0100210/// Stores information about a keyword argument
211struct argument_entry {
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100212 const char *name; ///< Argument name
213 const char *descr; ///< Human-readable version of the argument value
214 PyObject *value; ///< Associated Python object
Wenzel Jakob2ac50442016-01-17 22:36:35 +0100215
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100216 argument_entry(const char *name, const char *descr, PyObject *value)
Wenzel Jakob2ac50442016-01-17 22:36:35 +0100217 : name(name), descr(descr), value(value) { }
Wenzel Jakob2ac50442016-01-17 22:36:35 +0100218};
219
Wenzel Jakob43398a82015-07-28 16:12:20 +0200220/// Internal data struture used to track registered instances and types
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200221struct internals {
Wenzel Jakobf5fae922015-08-24 15:31:24 +0200222 std::unordered_map<const std::type_info *, type_info> registered_types;
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +0200223 std::unordered_map<const void *, PyObject *> registered_instances;
224 std::unordered_set<std::pair<const PyObject *, const char *>, overload_hash> inactive_overload_cache;
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200225};
226
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200227/// Return a reference to the current 'internals' information
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200228inline internals &get_internals();
229
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200230/// Index sequence for convenient template metaprogramming involving tuples
231template<size_t ...> struct index_sequence { };
232template<size_t N, size_t ...S> struct make_index_sequence : make_index_sequence <N - 1, N - 1, S...> { };
233template<size_t ...S> struct make_index_sequence <0, S...> { typedef index_sequence<S...> type; };
234
235/// Strip the class from a method type
236template <typename T> struct remove_class {};
237template <typename C, typename R, typename... A> struct remove_class<R (C::*)(A...)> { typedef R type(A...); };
238template <typename C, typename R, typename... A> struct remove_class<R (C::*)(A...) const> { typedef R type(A...); };
239
240/// Helper template to strip away type modifiers
Wenzel Jakob4177ed42016-01-17 22:36:38 +0100241template <typename T> struct intrinsic_type { typedef T type; };
242template <typename T> struct intrinsic_type<const T> { typedef typename intrinsic_type<T>::type type; };
243template <typename T> struct intrinsic_type<T*> { typedef typename intrinsic_type<T>::type type; };
244template <typename T> struct intrinsic_type<T&> { typedef typename intrinsic_type<T>::type type; };
245template <typename T> struct intrinsic_type<T&&> { typedef typename intrinsic_type<T>::type type; };
246template <typename T, size_t N> struct intrinsic_type<const T[N]> { typedef typename intrinsic_type<T>::type type; };
247template <typename T, size_t N> struct intrinsic_type<T[N]> { typedef typename intrinsic_type<T>::type type; };
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200248
249/// Helper type to replace 'void' in some expressions
250struct void_type { };
Wenzel Jakob281aa0e2015-07-30 15:29:00 +0200251
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +0200252/// to_string variant which also accepts strings
253template <typename T> inline typename std::enable_if<!std::is_enum<T>::value, std::string>::type
254to_string(const T &value) { return std::to_string(value); }
255template <> inline std::string to_string(const std::string &value) { return value; }
256template <typename T> inline typename std::enable_if<std::is_enum<T>::value, std::string>::type
257to_string(T value) { return std::to_string((int) value); }
258
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200259NAMESPACE_END(detail)
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +0200260
261// C++ bindings of core Python exceptions
262struct stop_iteration : public std::runtime_error { public: stop_iteration(const std::string &w="") : std::runtime_error(w) {} };
263struct index_error : public std::runtime_error { public: index_error(const std::string &w="") : std::runtime_error(w) {} };
264struct error_already_set : public std::runtime_error { public: error_already_set() : std::runtime_error(detail::error_string()) {} };
Wenzel Jakob8f4eb002015-10-15 18:13:33 +0200265/// Thrown when pybind11::cast or handle::call fail due to a type casting error
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +0200266struct cast_error : public std::runtime_error { public: cast_error(const std::string &w = "") : std::runtime_error(w) {} };
267
Wenzel Jakob8f4eb002015-10-15 18:13:33 +0200268NAMESPACE_END(pybind11)