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

    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
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35

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

#if !defined(PYTHON_EXPORT)
#if defined(WIN32)
#define PYTHON_EXPORT __declspec(dllexport)
#else
#define PYTHON_EXPORT __attribute__ ((visibility("default")))
#endif
#endif

#define PYTHON_PLUGIN(name) \
    extern "C" PYTHON_EXPORT PyObject *PyInit_##name()

#include <vector>
#include <string>
#include <stdexcept>
#include <unordered_map>
#include <iostream>
#include <memory>
Wenzel Jakob's avatar
Wenzel Jakob committed
36
#include <functional>
Wenzel Jakob's avatar
Wenzel Jakob committed
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

/// Include Python header, disable linking to pythonX_d.lib on Windows in debug mode
#if defined(_MSC_VER)
#define HAVE_ROUND
#pragma warning(push)
#pragma warning(disable: 4510 4610 4512)
#if _DEBUG
#define _DEBUG_MARKER
#undef _DEBUG
#endif
#endif
#include <Python.h>
#if defined(_MSC_VER)
#if defined(_DEBUG_MARKER)
#define _DEBUG
#undef _DEBUG_MARKER
#endif
#pragma warning(pop)
#endif

NAMESPACE_BEGIN(pybind)

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 { };
Wenzel Jakob's avatar
Wenzel Jakob committed
82
83
84
85
86
#define DECL_FMT(t, n) template<> struct format_descriptor<t> { static std::string value() { return n; }; };
DECL_FMT(int8_t,  "b"); DECL_FMT(uint8_t,  "B"); DECL_FMT(int16_t, "h"); DECL_FMT(uint16_t, "H");
DECL_FMT(int32_t, "i"); DECL_FMT(uint32_t, "I"); DECL_FMT(int64_t, "q"); DECL_FMT(uint64_t, "Q");
DECL_FMT(float ,  "f"); DECL_FMT(double,   "d");
#undef DECL_FMT
Wenzel Jakob's avatar
Wenzel Jakob committed
87
88
89
90

/// Information record describing a Python buffer object
struct buffer_info {
    void *ptr;
Wenzel Jakob's avatar
Wenzel Jakob committed
91
    size_t itemsize, count;
Wenzel Jakob's avatar
Wenzel Jakob committed
92
93
94
95
96
    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
97
98
    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
99
        : ptr(ptr), itemsize(itemsize), format(format), ndim(ndim),
Wenzel Jakob's avatar
Wenzel Jakob committed
100
101
102
          shape(shape), strides(strides) {
        count = 1; for (int i=0; i<ndim; ++i) count *= shape[i];
    }
Wenzel Jakob's avatar
Wenzel Jakob committed
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
};

// 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::exception     { public: error_already_set()                                               {} };
/// Thrown when pybind::cast or handle::call fail due to a type casting error
struct cast_error        : public std::runtime_error { public: cast_error(const std::string &w = "") : std::runtime_error(w) {} };

NAMESPACE_BEGIN(detail)

/// 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;
};

/// Additional type information which does not fit into the PyTypeObjet
struct type_info {
    PyTypeObject *type;
    size_t type_size;
    void (*init_holder)(PyObject *);
    std::function<buffer_info *(PyObject *)> get_buffer;
    std::vector<PyObject *(*)(PyObject *, PyTypeObject *)> implicit_conversions;
};

/// Internal data struture used to track registered instances and types 
struct internals {
    std::unordered_map<std::string, type_info> registered_types;
    std::unordered_map<void *, PyObject *> registered_instances;
};

Wenzel Jakob's avatar
Wenzel Jakob committed
139
/// Return a reference to the current 'internals' information
Wenzel Jakob's avatar
Wenzel Jakob committed
140
141
inline internals &get_internals();

Wenzel Jakob's avatar
Wenzel Jakob committed
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
/// 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 { };
Wenzel Jakob's avatar
Wenzel Jakob committed
163
164
NAMESPACE_END(detail)
NAMESPACE_END(pybind)