common.h 9.78 KB
Newer Older
Wenzel Jakob's avatar
Wenzel Jakob committed
1
/*
2
    pybind11/common.h -- Basic macros
Wenzel Jakob's avatar
Wenzel Jakob committed
3
4
5
6
7
8
9

    Copyright (c) 2015 Wenzel Jakob <wenzel@inf.ethz.ch>

    All rights reserved. Use of this source code is governed by a
    BSD-style license that can be found in the LICENSE file.
*/

10
#pragma once
Wenzel Jakob's avatar
Wenzel Jakob committed
11
12
13
14
15
16
17
18

#if !defined(NAMESPACE_BEGIN)
#define NAMESPACE_BEGIN(name) namespace name {
#endif
#if !defined(NAMESPACE_END)
#define NAMESPACE_END(name) }
#endif

19
#if !defined(PYBIND11_EXPORT)
Wenzel Jakob's avatar
Wenzel Jakob committed
20
#if defined(WIN32) || defined(_WIN32)
21
#define PYBIND11_EXPORT __declspec(dllexport)
Wenzel Jakob's avatar
Wenzel Jakob committed
22
#else
23
#define PYBIND11_EXPORT __attribute__ ((visibility("default")))
Wenzel Jakob's avatar
Wenzel Jakob committed
24
25
#endif
#endif
26
27
28
29
30
31
#if defined(_MSC_VER)
#define PYBIND11_NOINLINE __declspec(noinline)
#else
#define PYBIND11_NOINLINE __attribute__ ((noinline))
#endif

Wenzel Jakob's avatar
Wenzel Jakob committed
32
33
34
35

#include <vector>
#include <string>
#include <stdexcept>
36
#include <unordered_set>
Wenzel Jakob's avatar
Wenzel Jakob committed
37
38
39
40
41
42
43
#include <unordered_map>
#include <memory>

/// Include Python header, disable linking to pythonX_d.lib on Windows in debug mode
#if defined(_MSC_VER)
#define HAVE_ROUND
#pragma warning(push)
44
#pragma warning(disable: 4510 4610 4512 4005)
Wenzel Jakob's avatar
Wenzel Jakob committed
45
46
47
48
49
50
#if _DEBUG
#define _DEBUG_MARKER
#undef _DEBUG
#endif
#endif
#include <Python.h>
51
#include <frameobject.h>
52
53
54
55
56
57
58
59
60
#ifdef isalnum
#undef isalnum
#undef isalpha
#undef islower
#undef isspace
#undef isupper
#undef tolower
#undef toupper
#endif
Wenzel Jakob's avatar
Wenzel Jakob committed
61
62
63
64
65
66
67
68
#if defined(_MSC_VER)
#if defined(_DEBUG_MARKER)
#define _DEBUG
#undef _DEBUG_MARKER
#endif
#pragma warning(pop)
#endif

69
#if PY_MAJOR_VERSION >= 3
70
#define PYBIND11_PLUGIN_IMPL(name) \
71
    extern "C" PYBIND11_EXPORT PyObject *PyInit_##name()
72
#else
73
#define PYBIND11_PLUGIN_IMPL(name) \
74
    extern "C" PYBIND11_EXPORT PyObject *init##name()
75
#endif
76
77
78
79
80
81
82
83
84
85
86
87
#define PYBIND11_PLUGIN(name) \
    static PyObject *pybind11_init(); \
    PYBIND11_PLUGIN_IMPL(name) { \
        try { \
            return pybind11_init(); \
        } catch (const std::exception &e) { \
            PyErr_SetString(PyExc_ImportError, e.what()); \
            return nullptr; \
        } \
    } \
    PyObject *pybind11_init()

88
89
90
91
92
93
94
95
96
#if PY_MAJOR_VERSION >= 3 /// Compatibility macros for various Python versions
#define PYBIND11_BYTES_CHECK PyBytes_Check
#define PYBIND11_BYTES_FROM_STRING PyBytes_FromString
#define PYBIND11_BYTES_FROM_STRING_AND_SIZE PyBytes_FromStringAndSize
#define PYBIND11_BYTES_AS_STRING_AND_SIZE PyBytes_AsStringAndSize
#define PYBIND11_BYTES_AS_STRING PyBytes_AsString
#define PYBIND11_LONG_CHECK(o) PyLong_Check(o)
#define PYBIND11_LONG_AS_LONGLONG(o) PyLong_AsLongLong(o)
#define PYBIND11_LONG_AS_UNSIGNED_LONGLONG(o) PyLong_AsUnsignedLongLong(o)
97
#define PYBIND11_BYTES_NAME "bytes"
98
99
100
101
102
103
104
105
106
107
108
#define PYBIND11_STRING_NAME "str"
#define PYBIND11_SLICE_OBJECT PyObject
#else
#define PYBIND11_BYTES_CHECK PyString_Check
#define PYBIND11_BYTES_FROM_STRING PyString_FromString
#define PYBIND11_BYTES_FROM_STRING_AND_SIZE PyString_FromStringAndSize
#define PYBIND11_BYTES_AS_STRING_AND_SIZE PyString_AsStringAndSize
#define PYBIND11_BYTES_AS_STRING PyString_AsString
#define PYBIND11_LONG_CHECK(o) (PyInt_Check(o) || PyLong_Check(o))
#define PYBIND11_LONG_AS_LONGLONG(o) (PyInt_Check(o) ? (long long) PyLong_AsLong(o) : PyLong_AsLongLong(o))
#define PYBIND11_LONG_AS_UNSIGNED_LONGLONG(o) (PyInt_Check(o) ? (unsigned long long) PyLong_AsUnsignedLong(o) : PyLong_AsUnsignedLongLong(o))
109
#define PYBIND11_BYTES_NAME "str"
110
111
112
#define PYBIND11_STRING_NAME "unicode"
#define PYBIND11_SLICE_OBJECT PySliceObject
#endif
113

114
NAMESPACE_BEGIN(pybind11)
Wenzel Jakob's avatar
Wenzel Jakob committed
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138

typedef Py_ssize_t ssize_t;

/// Approach used to cast a previously unknown C++ instance into a Python object
enum class return_value_policy : int {
    /** Automatic: copy objects returned as values and take ownership of objects
        returned as pointers */
    automatic = 0,
    /** Reference the object and take ownership. Python will call the
        destructor and delete operator when the reference count reaches zero */
    take_ownership,
    /** Reference the object, but do not take ownership (dangerous when C++ code
        deletes it and Python still has a nonzero reference count) */
    reference,
    /** Reference the object, but do not take ownership. The object is considered
        be owned by the C++ instance whose method or property returned it. The
        Python object will increase the reference count of this 'parent' by 1 */
    reference_internal,
    /// Create a new copy of the returned object, which will be owned by Python
    copy
};

/// Format strings for basic number types
template <typename type> struct format_descriptor { };
139
140
141
142
#define PYBIND11_DECL_FMT(t, n) template<> struct format_descriptor<t> { static std::string value() { return n; }; };
PYBIND11_DECL_FMT(int8_t,  "b"); PYBIND11_DECL_FMT(uint8_t,  "B"); PYBIND11_DECL_FMT(int16_t, "h"); PYBIND11_DECL_FMT(uint16_t, "H");
PYBIND11_DECL_FMT(int32_t, "i"); PYBIND11_DECL_FMT(uint32_t, "I"); PYBIND11_DECL_FMT(int64_t, "q"); PYBIND11_DECL_FMT(uint64_t, "Q");
PYBIND11_DECL_FMT(float,   "f"); PYBIND11_DECL_FMT(double,   "d"); PYBIND11_DECL_FMT(bool,    "?");
Wenzel Jakob's avatar
Wenzel Jakob committed
143
144
145
146

/// Information record describing a Python buffer object
struct buffer_info {
    void *ptr;
Wenzel Jakob's avatar
Wenzel Jakob committed
147
    size_t itemsize, count;
Wenzel Jakob's avatar
Wenzel Jakob committed
148
149
150
151
152
    std::string format; // for dense contents, this should be set to format_descriptor<T>::value
    int ndim;
    std::vector<size_t> shape;
    std::vector<size_t> strides;

Wenzel Jakob's avatar
Wenzel Jakob committed
153
154
    buffer_info(void *ptr, size_t itemsize, const std::string &format, int ndim,
                const std::vector<size_t> &shape, const std::vector<size_t> &strides)
Wenzel Jakob's avatar
Wenzel Jakob committed
155
        : ptr(ptr), itemsize(itemsize), format(format), ndim(ndim),
Wenzel Jakob's avatar
Wenzel Jakob committed
156
157
158
          shape(shape), strides(strides) {
        count = 1; for (int i=0; i<ndim; ++i) count *= shape[i];
    }
Wenzel Jakob's avatar
Wenzel Jakob committed
159
160
161
162
};

NAMESPACE_BEGIN(detail)

163
164
inline std::string error_string();

Wenzel Jakob's avatar
Wenzel Jakob committed
165
166
167
168
169
170
171
172
173
174
/// PyObject wrapper around generic types
template <typename type, typename holder_type = std::unique_ptr<type>> struct instance {
    PyObject_HEAD
    type *value;
    PyObject *parent;
    bool owned : 1;
    bool constructed : 1;
    holder_type holder;
};

175
/// Additional type information which does not fit into the PyTypeObject
Wenzel Jakob's avatar
Wenzel Jakob committed
176
177
178
179
180
struct type_info {
    PyTypeObject *type;
    size_t type_size;
    void (*init_holder)(PyObject *);
    std::vector<PyObject *(*)(PyObject *, PyTypeObject *)> implicit_conversions;
Wenzel Jakob's avatar
Wenzel Jakob committed
181
182
    buffer_info *(*get_buffer)(PyObject *, void *) = nullptr;
    void *get_buffer_data = nullptr;
Wenzel Jakob's avatar
Wenzel Jakob committed
183
184
};

185
186
187
188
189
190
191
192
struct overload_hash {
    inline std::size_t operator()(const std::pair<const PyObject *, const char *>& v) const {
        size_t value = std::hash<const void *>()(v.first);
        value ^= std::hash<const void *>()(v.second)  + 0x9e3779b9 + (value<<6) + (value>>2);
        return value;
    }
};

193
194
/// Stores information about a keyword argument
struct argument_entry {
195
196
197
    const char *name;  ///< Argument name
    const char *descr; ///< Human-readable version of the argument value
    PyObject *value;   ///< Associated Python object
198

199
    argument_entry(const char *name, const char *descr, PyObject *value)
200
201
202
        : name(name), descr(descr), value(value) { }
};

Wenzel Jakob's avatar
Wenzel Jakob committed
203
/// Internal data struture used to track registered instances and types
Wenzel Jakob's avatar
Wenzel Jakob committed
204
struct internals {
205
    std::unordered_map<const std::type_info *, type_info> registered_types;
206
207
    std::unordered_map<const void *, PyObject *> registered_instances;
    std::unordered_set<std::pair<const PyObject *, const char *>, overload_hash> inactive_overload_cache;
Wenzel Jakob's avatar
Wenzel Jakob committed
208
209
};

Wenzel Jakob's avatar
Wenzel Jakob committed
210
/// Return a reference to the current 'internals' information
Wenzel Jakob's avatar
Wenzel Jakob committed
211
212
inline internals &get_internals();

Wenzel Jakob's avatar
Wenzel Jakob committed
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
/// Index sequence for convenient template metaprogramming involving tuples
template<size_t ...> struct index_sequence  { };
template<size_t N, size_t ...S> struct make_index_sequence : make_index_sequence <N - 1, N - 1, S...> { };
template<size_t ...S> struct make_index_sequence <0, S...> { typedef index_sequence<S...> type; };

/// Strip the class from a method type
template <typename T> struct remove_class {};
template <typename C, typename R, typename... A> struct remove_class<R (C::*)(A...)> { typedef R type(A...); };
template <typename C, typename R, typename... A> struct remove_class<R (C::*)(A...) const> { typedef R type(A...); };

/// Helper template to strip away type modifiers
template <typename T> struct decay                       { typedef T type; };
template <typename T> struct decay<const T>              { typedef typename decay<T>::type type; };
template <typename T> struct decay<T*>                   { typedef typename decay<T>::type type; };
template <typename T> struct decay<T&>                   { typedef typename decay<T>::type type; };
template <typename T> struct decay<T&&>                  { typedef typename decay<T>::type type; };
template <typename T, size_t N> struct decay<const T[N]> { typedef typename decay<T>::type type; };
template <typename T, size_t N> struct decay<T[N]>       { typedef typename decay<T>::type type; };

/// Helper type to replace 'void' in some expressions
struct void_type { };
234

235
236
237
238
239
240
241
/// to_string variant which also accepts strings
template <typename T> inline typename std::enable_if<!std::is_enum<T>::value, std::string>::type
to_string(const T &value) { return std::to_string(value); }
template <> inline std::string to_string(const std::string &value) { return value; }
template <typename T> inline typename std::enable_if<std::is_enum<T>::value, std::string>::type
to_string(T value) { return std::to_string((int) value); }

Wenzel Jakob's avatar
Wenzel Jakob committed
242
NAMESPACE_END(detail)
243
244
245
246
247

// C++ bindings of core Python exceptions
struct stop_iteration    : public std::runtime_error { public: stop_iteration(const std::string &w="") : std::runtime_error(w)   {} };
struct index_error       : public std::runtime_error { public: index_error(const std::string &w="")    : std::runtime_error(w)   {} };
struct error_already_set : public std::runtime_error { public: error_already_set() : std::runtime_error(detail::error_string())  {} };
248
/// Thrown when pybind11::cast or handle::call fail due to a type casting error
249
250
struct cast_error        : public std::runtime_error { public: cast_error(const std::string &w = "") : std::runtime_error(w)     {} };

251
NAMESPACE_END(pybind11)