numpy.h revision 12391:ceeca8b41e4b
1/* 2 pybind11/numpy.h: Basic NumPy support, vectorize() wrapper 3 4 Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.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 10#pragma once 11 12#include "pybind11.h" 13#include "complex.h" 14#include <numeric> 15#include <algorithm> 16#include <array> 17#include <cstdlib> 18#include <cstring> 19#include <sstream> 20#include <string> 21#include <initializer_list> 22#include <functional> 23#include <utility> 24#include <typeindex> 25 26#if defined(_MSC_VER) 27# pragma warning(push) 28# pragma warning(disable: 4127) // warning C4127: Conditional expression is constant 29#endif 30 31/* This will be true on all flat address space platforms and allows us to reduce the 32 whole npy_intp / ssize_t / Py_intptr_t business down to just ssize_t for all size 33 and dimension types (e.g. shape, strides, indexing), instead of inflicting this 34 upon the library user. */ 35static_assert(sizeof(ssize_t) == sizeof(Py_intptr_t), "ssize_t != Py_intptr_t"); 36 37NAMESPACE_BEGIN(PYBIND11_NAMESPACE) 38 39class array; // Forward declaration 40 41NAMESPACE_BEGIN(detail) 42template <typename type, typename SFINAE = void> struct npy_format_descriptor; 43 44struct PyArrayDescr_Proxy { 45 PyObject_HEAD 46 PyObject *typeobj; 47 char kind; 48 char type; 49 char byteorder; 50 char flags; 51 int type_num; 52 int elsize; 53 int alignment; 54 char *subarray; 55 PyObject *fields; 56 PyObject *names; 57}; 58 59struct PyArray_Proxy { 60 PyObject_HEAD 61 char *data; 62 int nd; 63 ssize_t *dimensions; 64 ssize_t *strides; 65 PyObject *base; 66 PyObject *descr; 67 int flags; 68}; 69 70struct PyVoidScalarObject_Proxy { 71 PyObject_VAR_HEAD 72 char *obval; 73 PyArrayDescr_Proxy *descr; 74 int flags; 75 PyObject *base; 76}; 77 78struct numpy_type_info { 79 PyObject* dtype_ptr; 80 std::string format_str; 81}; 82 83struct numpy_internals { 84 std::unordered_map<std::type_index, numpy_type_info> registered_dtypes; 85 86 numpy_type_info *get_type_info(const std::type_info& tinfo, bool throw_if_missing = true) { 87 auto it = registered_dtypes.find(std::type_index(tinfo)); 88 if (it != registered_dtypes.end()) 89 return &(it->second); 90 if (throw_if_missing) 91 pybind11_fail(std::string("NumPy type info missing for ") + tinfo.name()); 92 return nullptr; 93 } 94 95 template<typename T> numpy_type_info *get_type_info(bool throw_if_missing = true) { 96 return get_type_info(typeid(typename std::remove_cv<T>::type), throw_if_missing); 97 } 98}; 99 100inline PYBIND11_NOINLINE void load_numpy_internals(numpy_internals* &ptr) { 101 ptr = &get_or_create_shared_data<numpy_internals>("_numpy_internals"); 102} 103 104inline numpy_internals& get_numpy_internals() { 105 static numpy_internals* ptr = nullptr; 106 if (!ptr) 107 load_numpy_internals(ptr); 108 return *ptr; 109} 110 111struct npy_api { 112 enum constants { 113 NPY_ARRAY_C_CONTIGUOUS_ = 0x0001, 114 NPY_ARRAY_F_CONTIGUOUS_ = 0x0002, 115 NPY_ARRAY_OWNDATA_ = 0x0004, 116 NPY_ARRAY_FORCECAST_ = 0x0010, 117 NPY_ARRAY_ENSUREARRAY_ = 0x0040, 118 NPY_ARRAY_ALIGNED_ = 0x0100, 119 NPY_ARRAY_WRITEABLE_ = 0x0400, 120 NPY_BOOL_ = 0, 121 NPY_BYTE_, NPY_UBYTE_, 122 NPY_SHORT_, NPY_USHORT_, 123 NPY_INT_, NPY_UINT_, 124 NPY_LONG_, NPY_ULONG_, 125 NPY_LONGLONG_, NPY_ULONGLONG_, 126 NPY_FLOAT_, NPY_DOUBLE_, NPY_LONGDOUBLE_, 127 NPY_CFLOAT_, NPY_CDOUBLE_, NPY_CLONGDOUBLE_, 128 NPY_OBJECT_ = 17, 129 NPY_STRING_, NPY_UNICODE_, NPY_VOID_ 130 }; 131 132 typedef struct { 133 Py_intptr_t *ptr; 134 int len; 135 } PyArray_Dims; 136 137 static npy_api& get() { 138 static npy_api api = lookup(); 139 return api; 140 } 141 142 bool PyArray_Check_(PyObject *obj) const { 143 return (bool) PyObject_TypeCheck(obj, PyArray_Type_); 144 } 145 bool PyArrayDescr_Check_(PyObject *obj) const { 146 return (bool) PyObject_TypeCheck(obj, PyArrayDescr_Type_); 147 } 148 149 unsigned int (*PyArray_GetNDArrayCFeatureVersion_)(); 150 PyObject *(*PyArray_DescrFromType_)(int); 151 PyObject *(*PyArray_NewFromDescr_) 152 (PyTypeObject *, PyObject *, int, Py_intptr_t *, 153 Py_intptr_t *, void *, int, PyObject *); 154 PyObject *(*PyArray_DescrNewFromType_)(int); 155 int (*PyArray_CopyInto_)(PyObject *, PyObject *); 156 PyObject *(*PyArray_NewCopy_)(PyObject *, int); 157 PyTypeObject *PyArray_Type_; 158 PyTypeObject *PyVoidArrType_Type_; 159 PyTypeObject *PyArrayDescr_Type_; 160 PyObject *(*PyArray_DescrFromScalar_)(PyObject *); 161 PyObject *(*PyArray_FromAny_) (PyObject *, PyObject *, int, int, int, PyObject *); 162 int (*PyArray_DescrConverter_) (PyObject *, PyObject **); 163 bool (*PyArray_EquivTypes_) (PyObject *, PyObject *); 164 int (*PyArray_GetArrayParamsFromObject_)(PyObject *, PyObject *, char, PyObject **, int *, 165 Py_ssize_t *, PyObject **, PyObject *); 166 PyObject *(*PyArray_Squeeze_)(PyObject *); 167 int (*PyArray_SetBaseObject_)(PyObject *, PyObject *); 168 PyObject* (*PyArray_Resize_)(PyObject*, PyArray_Dims*, int, int); 169private: 170 enum functions { 171 API_PyArray_GetNDArrayCFeatureVersion = 211, 172 API_PyArray_Type = 2, 173 API_PyArrayDescr_Type = 3, 174 API_PyVoidArrType_Type = 39, 175 API_PyArray_DescrFromType = 45, 176 API_PyArray_DescrFromScalar = 57, 177 API_PyArray_FromAny = 69, 178 API_PyArray_Resize = 80, 179 API_PyArray_CopyInto = 82, 180 API_PyArray_NewCopy = 85, 181 API_PyArray_NewFromDescr = 94, 182 API_PyArray_DescrNewFromType = 9, 183 API_PyArray_DescrConverter = 174, 184 API_PyArray_EquivTypes = 182, 185 API_PyArray_GetArrayParamsFromObject = 278, 186 API_PyArray_Squeeze = 136, 187 API_PyArray_SetBaseObject = 282 188 }; 189 190 static npy_api lookup() { 191 module m = module::import("numpy.core.multiarray"); 192 auto c = m.attr("_ARRAY_API"); 193#if PY_MAJOR_VERSION >= 3 194 void **api_ptr = (void **) PyCapsule_GetPointer(c.ptr(), NULL); 195#else 196 void **api_ptr = (void **) PyCObject_AsVoidPtr(c.ptr()); 197#endif 198 npy_api api; 199#define DECL_NPY_API(Func) api.Func##_ = (decltype(api.Func##_)) api_ptr[API_##Func]; 200 DECL_NPY_API(PyArray_GetNDArrayCFeatureVersion); 201 if (api.PyArray_GetNDArrayCFeatureVersion_() < 0x7) 202 pybind11_fail("pybind11 numpy support requires numpy >= 1.7.0"); 203 DECL_NPY_API(PyArray_Type); 204 DECL_NPY_API(PyVoidArrType_Type); 205 DECL_NPY_API(PyArrayDescr_Type); 206 DECL_NPY_API(PyArray_DescrFromType); 207 DECL_NPY_API(PyArray_DescrFromScalar); 208 DECL_NPY_API(PyArray_FromAny); 209 DECL_NPY_API(PyArray_Resize); 210 DECL_NPY_API(PyArray_CopyInto); 211 DECL_NPY_API(PyArray_NewCopy); 212 DECL_NPY_API(PyArray_NewFromDescr); 213 DECL_NPY_API(PyArray_DescrNewFromType); 214 DECL_NPY_API(PyArray_DescrConverter); 215 DECL_NPY_API(PyArray_EquivTypes); 216 DECL_NPY_API(PyArray_GetArrayParamsFromObject); 217 DECL_NPY_API(PyArray_Squeeze); 218 DECL_NPY_API(PyArray_SetBaseObject); 219#undef DECL_NPY_API 220 return api; 221 } 222}; 223 224inline PyArray_Proxy* array_proxy(void* ptr) { 225 return reinterpret_cast<PyArray_Proxy*>(ptr); 226} 227 228inline const PyArray_Proxy* array_proxy(const void* ptr) { 229 return reinterpret_cast<const PyArray_Proxy*>(ptr); 230} 231 232inline PyArrayDescr_Proxy* array_descriptor_proxy(PyObject* ptr) { 233 return reinterpret_cast<PyArrayDescr_Proxy*>(ptr); 234} 235 236inline const PyArrayDescr_Proxy* array_descriptor_proxy(const PyObject* ptr) { 237 return reinterpret_cast<const PyArrayDescr_Proxy*>(ptr); 238} 239 240inline bool check_flags(const void* ptr, int flag) { 241 return (flag == (array_proxy(ptr)->flags & flag)); 242} 243 244template <typename T> struct is_std_array : std::false_type { }; 245template <typename T, size_t N> struct is_std_array<std::array<T, N>> : std::true_type { }; 246template <typename T> struct is_complex : std::false_type { }; 247template <typename T> struct is_complex<std::complex<T>> : std::true_type { }; 248 249template <typename T> struct array_info_scalar { 250 typedef T type; 251 static constexpr bool is_array = false; 252 static constexpr bool is_empty = false; 253 static PYBIND11_DESCR extents() { return _(""); } 254 static void append_extents(list& /* shape */) { } 255}; 256// Computes underlying type and a comma-separated list of extents for array 257// types (any mix of std::array and built-in arrays). An array of char is 258// treated as scalar because it gets special handling. 259template <typename T> struct array_info : array_info_scalar<T> { }; 260template <typename T, size_t N> struct array_info<std::array<T, N>> { 261 using type = typename array_info<T>::type; 262 static constexpr bool is_array = true; 263 static constexpr bool is_empty = (N == 0) || array_info<T>::is_empty; 264 static constexpr size_t extent = N; 265 266 // appends the extents to shape 267 static void append_extents(list& shape) { 268 shape.append(N); 269 array_info<T>::append_extents(shape); 270 } 271 272 template<typename T2 = T, enable_if_t<!array_info<T2>::is_array, int> = 0> 273 static PYBIND11_DESCR extents() { 274 return _<N>(); 275 } 276 277 template<typename T2 = T, enable_if_t<array_info<T2>::is_array, int> = 0> 278 static PYBIND11_DESCR extents() { 279 return concat(_<N>(), array_info<T>::extents()); 280 } 281}; 282// For numpy we have special handling for arrays of characters, so we don't include 283// the size in the array extents. 284template <size_t N> struct array_info<char[N]> : array_info_scalar<char[N]> { }; 285template <size_t N> struct array_info<std::array<char, N>> : array_info_scalar<std::array<char, N>> { }; 286template <typename T, size_t N> struct array_info<T[N]> : array_info<std::array<T, N>> { }; 287template <typename T> using remove_all_extents_t = typename array_info<T>::type; 288 289template <typename T> using is_pod_struct = all_of< 290 std::is_standard_layout<T>, // since we're accessing directly in memory we need a standard layout type 291#if !defined(__GNUG__) || defined(_LIBCPP_VERSION) || defined(_GLIBCXX_USE_CXX11_ABI) 292 // _GLIBCXX_USE_CXX11_ABI indicates that we're using libstdc++ from GCC 5 or newer, independent 293 // of the actual compiler (Clang can also use libstdc++, but it always defines __GNUC__ == 4). 294 std::is_trivially_copyable<T>, 295#else 296 // GCC 4 doesn't implement is_trivially_copyable, so approximate it 297 std::is_trivially_destructible<T>, 298 satisfies_any_of<T, std::has_trivial_copy_constructor, std::has_trivial_copy_assign>, 299#endif 300 satisfies_none_of<T, std::is_reference, std::is_array, is_std_array, std::is_arithmetic, is_complex, std::is_enum> 301>; 302 303template <ssize_t Dim = 0, typename Strides> ssize_t byte_offset_unsafe(const Strides &) { return 0; } 304template <ssize_t Dim = 0, typename Strides, typename... Ix> 305ssize_t byte_offset_unsafe(const Strides &strides, ssize_t i, Ix... index) { 306 return i * strides[Dim] + byte_offset_unsafe<Dim + 1>(strides, index...); 307} 308 309/** 310 * Proxy class providing unsafe, unchecked const access to array data. This is constructed through 311 * the `unchecked<T, N>()` method of `array` or the `unchecked<N>()` method of `array_t<T>`. `Dims` 312 * will be -1 for dimensions determined at runtime. 313 */ 314template <typename T, ssize_t Dims> 315class unchecked_reference { 316protected: 317 static constexpr bool Dynamic = Dims < 0; 318 const unsigned char *data_; 319 // Storing the shape & strides in local variables (i.e. these arrays) allows the compiler to 320 // make large performance gains on big, nested loops, but requires compile-time dimensions 321 conditional_t<Dynamic, const ssize_t *, std::array<ssize_t, (size_t) Dims>> 322 shape_, strides_; 323 const ssize_t dims_; 324 325 friend class pybind11::array; 326 // Constructor for compile-time dimensions: 327 template <bool Dyn = Dynamic> 328 unchecked_reference(const void *data, const ssize_t *shape, const ssize_t *strides, enable_if_t<!Dyn, ssize_t>) 329 : data_{reinterpret_cast<const unsigned char *>(data)}, dims_{Dims} { 330 for (size_t i = 0; i < (size_t) dims_; i++) { 331 shape_[i] = shape[i]; 332 strides_[i] = strides[i]; 333 } 334 } 335 // Constructor for runtime dimensions: 336 template <bool Dyn = Dynamic> 337 unchecked_reference(const void *data, const ssize_t *shape, const ssize_t *strides, enable_if_t<Dyn, ssize_t> dims) 338 : data_{reinterpret_cast<const unsigned char *>(data)}, shape_{shape}, strides_{strides}, dims_{dims} {} 339 340public: 341 /** 342 * Unchecked const reference access to data at the given indices. For a compile-time known 343 * number of dimensions, this requires the correct number of arguments; for run-time 344 * dimensionality, this is not checked (and so is up to the caller to use safely). 345 */ 346 template <typename... Ix> const T &operator()(Ix... index) const { 347 static_assert(ssize_t{sizeof...(Ix)} == Dims || Dynamic, 348 "Invalid number of indices for unchecked array reference"); 349 return *reinterpret_cast<const T *>(data_ + byte_offset_unsafe(strides_, ssize_t(index)...)); 350 } 351 /** 352 * Unchecked const reference access to data; this operator only participates if the reference 353 * is to a 1-dimensional array. When present, this is exactly equivalent to `obj(index)`. 354 */ 355 template <ssize_t D = Dims, typename = enable_if_t<D == 1 || Dynamic>> 356 const T &operator[](ssize_t index) const { return operator()(index); } 357 358 /// Pointer access to the data at the given indices. 359 template <typename... Ix> const T *data(Ix... ix) const { return &operator()(ssize_t(ix)...); } 360 361 /// Returns the item size, i.e. sizeof(T) 362 constexpr static ssize_t itemsize() { return sizeof(T); } 363 364 /// Returns the shape (i.e. size) of dimension `dim` 365 ssize_t shape(ssize_t dim) const { return shape_[(size_t) dim]; } 366 367 /// Returns the number of dimensions of the array 368 ssize_t ndim() const { return dims_; } 369 370 /// Returns the total number of elements in the referenced array, i.e. the product of the shapes 371 template <bool Dyn = Dynamic> 372 enable_if_t<!Dyn, ssize_t> size() const { 373 return std::accumulate(shape_.begin(), shape_.end(), (ssize_t) 1, std::multiplies<ssize_t>()); 374 } 375 template <bool Dyn = Dynamic> 376 enable_if_t<Dyn, ssize_t> size() const { 377 return std::accumulate(shape_, shape_ + ndim(), (ssize_t) 1, std::multiplies<ssize_t>()); 378 } 379 380 /// Returns the total number of bytes used by the referenced data. Note that the actual span in 381 /// memory may be larger if the referenced array has non-contiguous strides (e.g. for a slice). 382 ssize_t nbytes() const { 383 return size() * itemsize(); 384 } 385}; 386 387template <typename T, ssize_t Dims> 388class unchecked_mutable_reference : public unchecked_reference<T, Dims> { 389 friend class pybind11::array; 390 using ConstBase = unchecked_reference<T, Dims>; 391 using ConstBase::ConstBase; 392 using ConstBase::Dynamic; 393public: 394 /// Mutable, unchecked access to data at the given indices. 395 template <typename... Ix> T& operator()(Ix... index) { 396 static_assert(ssize_t{sizeof...(Ix)} == Dims || Dynamic, 397 "Invalid number of indices for unchecked array reference"); 398 return const_cast<T &>(ConstBase::operator()(index...)); 399 } 400 /** 401 * Mutable, unchecked access data at the given index; this operator only participates if the 402 * reference is to a 1-dimensional array (or has runtime dimensions). When present, this is 403 * exactly equivalent to `obj(index)`. 404 */ 405 template <ssize_t D = Dims, typename = enable_if_t<D == 1 || Dynamic>> 406 T &operator[](ssize_t index) { return operator()(index); } 407 408 /// Mutable pointer access to the data at the given indices. 409 template <typename... Ix> T *mutable_data(Ix... ix) { return &operator()(ssize_t(ix)...); } 410}; 411 412template <typename T, ssize_t Dim> 413struct type_caster<unchecked_reference<T, Dim>> { 414 static_assert(Dim == 0 && Dim > 0 /* always fail */, "unchecked array proxy object is not castable"); 415}; 416template <typename T, ssize_t Dim> 417struct type_caster<unchecked_mutable_reference<T, Dim>> : type_caster<unchecked_reference<T, Dim>> {}; 418 419NAMESPACE_END(detail) 420 421class dtype : public object { 422public: 423 PYBIND11_OBJECT_DEFAULT(dtype, object, detail::npy_api::get().PyArrayDescr_Check_); 424 425 explicit dtype(const buffer_info &info) { 426 dtype descr(_dtype_from_pep3118()(PYBIND11_STR_TYPE(info.format))); 427 // If info.itemsize == 0, use the value calculated from the format string 428 m_ptr = descr.strip_padding(info.itemsize ? info.itemsize : descr.itemsize()).release().ptr(); 429 } 430 431 explicit dtype(const std::string &format) { 432 m_ptr = from_args(pybind11::str(format)).release().ptr(); 433 } 434 435 dtype(const char *format) : dtype(std::string(format)) { } 436 437 dtype(list names, list formats, list offsets, ssize_t itemsize) { 438 dict args; 439 args["names"] = names; 440 args["formats"] = formats; 441 args["offsets"] = offsets; 442 args["itemsize"] = pybind11::int_(itemsize); 443 m_ptr = from_args(args).release().ptr(); 444 } 445 446 /// This is essentially the same as calling numpy.dtype(args) in Python. 447 static dtype from_args(object args) { 448 PyObject *ptr = nullptr; 449 if (!detail::npy_api::get().PyArray_DescrConverter_(args.release().ptr(), &ptr) || !ptr) 450 throw error_already_set(); 451 return reinterpret_steal<dtype>(ptr); 452 } 453 454 /// Return dtype associated with a C++ type. 455 template <typename T> static dtype of() { 456 return detail::npy_format_descriptor<typename std::remove_cv<T>::type>::dtype(); 457 } 458 459 /// Size of the data type in bytes. 460 ssize_t itemsize() const { 461 return detail::array_descriptor_proxy(m_ptr)->elsize; 462 } 463 464 /// Returns true for structured data types. 465 bool has_fields() const { 466 return detail::array_descriptor_proxy(m_ptr)->names != nullptr; 467 } 468 469 /// Single-character type code. 470 char kind() const { 471 return detail::array_descriptor_proxy(m_ptr)->kind; 472 } 473 474private: 475 static object _dtype_from_pep3118() { 476 static PyObject *obj = module::import("numpy.core._internal") 477 .attr("_dtype_from_pep3118").cast<object>().release().ptr(); 478 return reinterpret_borrow<object>(obj); 479 } 480 481 dtype strip_padding(ssize_t itemsize) { 482 // Recursively strip all void fields with empty names that are generated for 483 // padding fields (as of NumPy v1.11). 484 if (!has_fields()) 485 return *this; 486 487 struct field_descr { PYBIND11_STR_TYPE name; object format; pybind11::int_ offset; }; 488 std::vector<field_descr> field_descriptors; 489 490 for (auto field : attr("fields").attr("items")()) { 491 auto spec = field.cast<tuple>(); 492 auto name = spec[0].cast<pybind11::str>(); 493 auto format = spec[1].cast<tuple>()[0].cast<dtype>(); 494 auto offset = spec[1].cast<tuple>()[1].cast<pybind11::int_>(); 495 if (!len(name) && format.kind() == 'V') 496 continue; 497 field_descriptors.push_back({(PYBIND11_STR_TYPE) name, format.strip_padding(format.itemsize()), offset}); 498 } 499 500 std::sort(field_descriptors.begin(), field_descriptors.end(), 501 [](const field_descr& a, const field_descr& b) { 502 return a.offset.cast<int>() < b.offset.cast<int>(); 503 }); 504 505 list names, formats, offsets; 506 for (auto& descr : field_descriptors) { 507 names.append(descr.name); 508 formats.append(descr.format); 509 offsets.append(descr.offset); 510 } 511 return dtype(names, formats, offsets, itemsize); 512 } 513}; 514 515class array : public buffer { 516public: 517 PYBIND11_OBJECT_CVT(array, buffer, detail::npy_api::get().PyArray_Check_, raw_array) 518 519 enum { 520 c_style = detail::npy_api::NPY_ARRAY_C_CONTIGUOUS_, 521 f_style = detail::npy_api::NPY_ARRAY_F_CONTIGUOUS_, 522 forcecast = detail::npy_api::NPY_ARRAY_FORCECAST_ 523 }; 524 525 array() : array({{0}}, static_cast<const double *>(nullptr)) {} 526 527 using ShapeContainer = detail::any_container<ssize_t>; 528 using StridesContainer = detail::any_container<ssize_t>; 529 530 // Constructs an array taking shape/strides from arbitrary container types 531 array(const pybind11::dtype &dt, ShapeContainer shape, StridesContainer strides, 532 const void *ptr = nullptr, handle base = handle()) { 533 534 if (strides->empty()) 535 *strides = c_strides(*shape, dt.itemsize()); 536 537 auto ndim = shape->size(); 538 if (ndim != strides->size()) 539 pybind11_fail("NumPy: shape ndim doesn't match strides ndim"); 540 auto descr = dt; 541 542 int flags = 0; 543 if (base && ptr) { 544 if (isinstance<array>(base)) 545 /* Copy flags from base (except ownership bit) */ 546 flags = reinterpret_borrow<array>(base).flags() & ~detail::npy_api::NPY_ARRAY_OWNDATA_; 547 else 548 /* Writable by default, easy to downgrade later on if needed */ 549 flags = detail::npy_api::NPY_ARRAY_WRITEABLE_; 550 } 551 552 auto &api = detail::npy_api::get(); 553 auto tmp = reinterpret_steal<object>(api.PyArray_NewFromDescr_( 554 api.PyArray_Type_, descr.release().ptr(), (int) ndim, shape->data(), strides->data(), 555 const_cast<void *>(ptr), flags, nullptr)); 556 if (!tmp) 557 throw error_already_set(); 558 if (ptr) { 559 if (base) { 560 api.PyArray_SetBaseObject_(tmp.ptr(), base.inc_ref().ptr()); 561 } else { 562 tmp = reinterpret_steal<object>(api.PyArray_NewCopy_(tmp.ptr(), -1 /* any order */)); 563 } 564 } 565 m_ptr = tmp.release().ptr(); 566 } 567 568 array(const pybind11::dtype &dt, ShapeContainer shape, const void *ptr = nullptr, handle base = handle()) 569 : array(dt, std::move(shape), {}, ptr, base) { } 570 571 template <typename T, typename = detail::enable_if_t<std::is_integral<T>::value && !std::is_same<bool, T>::value>> 572 array(const pybind11::dtype &dt, T count, const void *ptr = nullptr, handle base = handle()) 573 : array(dt, {{count}}, ptr, base) { } 574 575 template <typename T> 576 array(ShapeContainer shape, StridesContainer strides, const T *ptr, handle base = handle()) 577 : array(pybind11::dtype::of<T>(), std::move(shape), std::move(strides), ptr, base) { } 578 579 template <typename T> 580 array(ShapeContainer shape, const T *ptr, handle base = handle()) 581 : array(std::move(shape), {}, ptr, base) { } 582 583 template <typename T> 584 explicit array(ssize_t count, const T *ptr, handle base = handle()) : array({count}, {}, ptr, base) { } 585 586 explicit array(const buffer_info &info) 587 : array(pybind11::dtype(info), info.shape, info.strides, info.ptr) { } 588 589 /// Array descriptor (dtype) 590 pybind11::dtype dtype() const { 591 return reinterpret_borrow<pybind11::dtype>(detail::array_proxy(m_ptr)->descr); 592 } 593 594 /// Total number of elements 595 ssize_t size() const { 596 return std::accumulate(shape(), shape() + ndim(), (ssize_t) 1, std::multiplies<ssize_t>()); 597 } 598 599 /// Byte size of a single element 600 ssize_t itemsize() const { 601 return detail::array_descriptor_proxy(detail::array_proxy(m_ptr)->descr)->elsize; 602 } 603 604 /// Total number of bytes 605 ssize_t nbytes() const { 606 return size() * itemsize(); 607 } 608 609 /// Number of dimensions 610 ssize_t ndim() const { 611 return detail::array_proxy(m_ptr)->nd; 612 } 613 614 /// Base object 615 object base() const { 616 return reinterpret_borrow<object>(detail::array_proxy(m_ptr)->base); 617 } 618 619 /// Dimensions of the array 620 const ssize_t* shape() const { 621 return detail::array_proxy(m_ptr)->dimensions; 622 } 623 624 /// Dimension along a given axis 625 ssize_t shape(ssize_t dim) const { 626 if (dim >= ndim()) 627 fail_dim_check(dim, "invalid axis"); 628 return shape()[dim]; 629 } 630 631 /// Strides of the array 632 const ssize_t* strides() const { 633 return detail::array_proxy(m_ptr)->strides; 634 } 635 636 /// Stride along a given axis 637 ssize_t strides(ssize_t dim) const { 638 if (dim >= ndim()) 639 fail_dim_check(dim, "invalid axis"); 640 return strides()[dim]; 641 } 642 643 /// Return the NumPy array flags 644 int flags() const { 645 return detail::array_proxy(m_ptr)->flags; 646 } 647 648 /// If set, the array is writeable (otherwise the buffer is read-only) 649 bool writeable() const { 650 return detail::check_flags(m_ptr, detail::npy_api::NPY_ARRAY_WRITEABLE_); 651 } 652 653 /// If set, the array owns the data (will be freed when the array is deleted) 654 bool owndata() const { 655 return detail::check_flags(m_ptr, detail::npy_api::NPY_ARRAY_OWNDATA_); 656 } 657 658 /// Pointer to the contained data. If index is not provided, points to the 659 /// beginning of the buffer. May throw if the index would lead to out of bounds access. 660 template<typename... Ix> const void* data(Ix... index) const { 661 return static_cast<const void *>(detail::array_proxy(m_ptr)->data + offset_at(index...)); 662 } 663 664 /// Mutable pointer to the contained data. If index is not provided, points to the 665 /// beginning of the buffer. May throw if the index would lead to out of bounds access. 666 /// May throw if the array is not writeable. 667 template<typename... Ix> void* mutable_data(Ix... index) { 668 check_writeable(); 669 return static_cast<void *>(detail::array_proxy(m_ptr)->data + offset_at(index...)); 670 } 671 672 /// Byte offset from beginning of the array to a given index (full or partial). 673 /// May throw if the index would lead to out of bounds access. 674 template<typename... Ix> ssize_t offset_at(Ix... index) const { 675 if ((ssize_t) sizeof...(index) > ndim()) 676 fail_dim_check(sizeof...(index), "too many indices for an array"); 677 return byte_offset(ssize_t(index)...); 678 } 679 680 ssize_t offset_at() const { return 0; } 681 682 /// Item count from beginning of the array to a given index (full or partial). 683 /// May throw if the index would lead to out of bounds access. 684 template<typename... Ix> ssize_t index_at(Ix... index) const { 685 return offset_at(index...) / itemsize(); 686 } 687 688 /** 689 * Returns a proxy object that provides access to the array's data without bounds or 690 * dimensionality checking. Will throw if the array is missing the `writeable` flag. Use with 691 * care: the array must not be destroyed or reshaped for the duration of the returned object, 692 * and the caller must take care not to access invalid dimensions or dimension indices. 693 */ 694 template <typename T, ssize_t Dims = -1> detail::unchecked_mutable_reference<T, Dims> mutable_unchecked() & { 695 if (Dims >= 0 && ndim() != Dims) 696 throw std::domain_error("array has incorrect number of dimensions: " + std::to_string(ndim()) + 697 "; expected " + std::to_string(Dims)); 698 return detail::unchecked_mutable_reference<T, Dims>(mutable_data(), shape(), strides(), ndim()); 699 } 700 701 /** 702 * Returns a proxy object that provides const access to the array's data without bounds or 703 * dimensionality checking. Unlike `mutable_unchecked()`, this does not require that the 704 * underlying array have the `writable` flag. Use with care: the array must not be destroyed or 705 * reshaped for the duration of the returned object, and the caller must take care not to access 706 * invalid dimensions or dimension indices. 707 */ 708 template <typename T, ssize_t Dims = -1> detail::unchecked_reference<T, Dims> unchecked() const & { 709 if (Dims >= 0 && ndim() != Dims) 710 throw std::domain_error("array has incorrect number of dimensions: " + std::to_string(ndim()) + 711 "; expected " + std::to_string(Dims)); 712 return detail::unchecked_reference<T, Dims>(data(), shape(), strides(), ndim()); 713 } 714 715 /// Return a new view with all of the dimensions of length 1 removed 716 array squeeze() { 717 auto& api = detail::npy_api::get(); 718 return reinterpret_steal<array>(api.PyArray_Squeeze_(m_ptr)); 719 } 720 721 /// Resize array to given shape 722 /// If refcheck is true and more that one reference exist to this array 723 /// then resize will succeed only if it makes a reshape, i.e. original size doesn't change 724 void resize(ShapeContainer new_shape, bool refcheck = true) { 725 detail::npy_api::PyArray_Dims d = { 726 new_shape->data(), int(new_shape->size()) 727 }; 728 // try to resize, set ordering param to -1 cause it's not used anyway 729 object new_array = reinterpret_steal<object>( 730 detail::npy_api::get().PyArray_Resize_(m_ptr, &d, int(refcheck), -1) 731 ); 732 if (!new_array) throw error_already_set(); 733 if (isinstance<array>(new_array)) { *this = std::move(new_array); } 734 } 735 736 /// Ensure that the argument is a NumPy array 737 /// In case of an error, nullptr is returned and the Python error is cleared. 738 static array ensure(handle h, int ExtraFlags = 0) { 739 auto result = reinterpret_steal<array>(raw_array(h.ptr(), ExtraFlags)); 740 if (!result) 741 PyErr_Clear(); 742 return result; 743 } 744 745protected: 746 template<typename, typename> friend struct detail::npy_format_descriptor; 747 748 void fail_dim_check(ssize_t dim, const std::string& msg) const { 749 throw index_error(msg + ": " + std::to_string(dim) + 750 " (ndim = " + std::to_string(ndim()) + ")"); 751 } 752 753 template<typename... Ix> ssize_t byte_offset(Ix... index) const { 754 check_dimensions(index...); 755 return detail::byte_offset_unsafe(strides(), ssize_t(index)...); 756 } 757 758 void check_writeable() const { 759 if (!writeable()) 760 throw std::domain_error("array is not writeable"); 761 } 762 763 // Default, C-style strides 764 static std::vector<ssize_t> c_strides(const std::vector<ssize_t> &shape, ssize_t itemsize) { 765 auto ndim = shape.size(); 766 std::vector<ssize_t> strides(ndim, itemsize); 767 for (size_t i = ndim - 1; i > 0; --i) 768 strides[i - 1] = strides[i] * shape[i]; 769 return strides; 770 } 771 772 // F-style strides; default when constructing an array_t with `ExtraFlags & f_style` 773 static std::vector<ssize_t> f_strides(const std::vector<ssize_t> &shape, ssize_t itemsize) { 774 auto ndim = shape.size(); 775 std::vector<ssize_t> strides(ndim, itemsize); 776 for (size_t i = 1; i < ndim; ++i) 777 strides[i] = strides[i - 1] * shape[i - 1]; 778 return strides; 779 } 780 781 template<typename... Ix> void check_dimensions(Ix... index) const { 782 check_dimensions_impl(ssize_t(0), shape(), ssize_t(index)...); 783 } 784 785 void check_dimensions_impl(ssize_t, const ssize_t*) const { } 786 787 template<typename... Ix> void check_dimensions_impl(ssize_t axis, const ssize_t* shape, ssize_t i, Ix... index) const { 788 if (i >= *shape) { 789 throw index_error(std::string("index ") + std::to_string(i) + 790 " is out of bounds for axis " + std::to_string(axis) + 791 " with size " + std::to_string(*shape)); 792 } 793 check_dimensions_impl(axis + 1, shape + 1, index...); 794 } 795 796 /// Create array from any object -- always returns a new reference 797 static PyObject *raw_array(PyObject *ptr, int ExtraFlags = 0) { 798 if (ptr == nullptr) { 799 PyErr_SetString(PyExc_ValueError, "cannot create a pybind11::array from a nullptr"); 800 return nullptr; 801 } 802 return detail::npy_api::get().PyArray_FromAny_( 803 ptr, nullptr, 0, 0, detail::npy_api::NPY_ARRAY_ENSUREARRAY_ | ExtraFlags, nullptr); 804 } 805}; 806 807template <typename T, int ExtraFlags = array::forcecast> class array_t : public array { 808private: 809 struct private_ctor {}; 810 // Delegating constructor needed when both moving and accessing in the same constructor 811 array_t(private_ctor, ShapeContainer &&shape, StridesContainer &&strides, const T *ptr, handle base) 812 : array(std::move(shape), std::move(strides), ptr, base) {} 813public: 814 static_assert(!detail::array_info<T>::is_array, "Array types cannot be used with array_t"); 815 816 using value_type = T; 817 818 array_t() : array(0, static_cast<const T *>(nullptr)) {} 819 array_t(handle h, borrowed_t) : array(h, borrowed_t{}) { } 820 array_t(handle h, stolen_t) : array(h, stolen_t{}) { } 821 822 PYBIND11_DEPRECATED("Use array_t<T>::ensure() instead") 823 array_t(handle h, bool is_borrowed) : array(raw_array_t(h.ptr()), stolen_t{}) { 824 if (!m_ptr) PyErr_Clear(); 825 if (!is_borrowed) Py_XDECREF(h.ptr()); 826 } 827 828 array_t(const object &o) : array(raw_array_t(o.ptr()), stolen_t{}) { 829 if (!m_ptr) throw error_already_set(); 830 } 831 832 explicit array_t(const buffer_info& info) : array(info) { } 833 834 array_t(ShapeContainer shape, StridesContainer strides, const T *ptr = nullptr, handle base = handle()) 835 : array(std::move(shape), std::move(strides), ptr, base) { } 836 837 explicit array_t(ShapeContainer shape, const T *ptr = nullptr, handle base = handle()) 838 : array_t(private_ctor{}, std::move(shape), 839 ExtraFlags & f_style ? f_strides(*shape, itemsize()) : c_strides(*shape, itemsize()), 840 ptr, base) { } 841 842 explicit array_t(size_t count, const T *ptr = nullptr, handle base = handle()) 843 : array({count}, {}, ptr, base) { } 844 845 constexpr ssize_t itemsize() const { 846 return sizeof(T); 847 } 848 849 template<typename... Ix> ssize_t index_at(Ix... index) const { 850 return offset_at(index...) / itemsize(); 851 } 852 853 template<typename... Ix> const T* data(Ix... index) const { 854 return static_cast<const T*>(array::data(index...)); 855 } 856 857 template<typename... Ix> T* mutable_data(Ix... index) { 858 return static_cast<T*>(array::mutable_data(index...)); 859 } 860 861 // Reference to element at a given index 862 template<typename... Ix> const T& at(Ix... index) const { 863 if (sizeof...(index) != ndim()) 864 fail_dim_check(sizeof...(index), "index dimension mismatch"); 865 return *(static_cast<const T*>(array::data()) + byte_offset(ssize_t(index)...) / itemsize()); 866 } 867 868 // Mutable reference to element at a given index 869 template<typename... Ix> T& mutable_at(Ix... index) { 870 if (sizeof...(index) != ndim()) 871 fail_dim_check(sizeof...(index), "index dimension mismatch"); 872 return *(static_cast<T*>(array::mutable_data()) + byte_offset(ssize_t(index)...) / itemsize()); 873 } 874 875 /** 876 * Returns a proxy object that provides access to the array's data without bounds or 877 * dimensionality checking. Will throw if the array is missing the `writeable` flag. Use with 878 * care: the array must not be destroyed or reshaped for the duration of the returned object, 879 * and the caller must take care not to access invalid dimensions or dimension indices. 880 */ 881 template <ssize_t Dims = -1> detail::unchecked_mutable_reference<T, Dims> mutable_unchecked() & { 882 return array::mutable_unchecked<T, Dims>(); 883 } 884 885 /** 886 * Returns a proxy object that provides const access to the array's data without bounds or 887 * dimensionality checking. Unlike `unchecked()`, this does not require that the underlying 888 * array have the `writable` flag. Use with care: the array must not be destroyed or reshaped 889 * for the duration of the returned object, and the caller must take care not to access invalid 890 * dimensions or dimension indices. 891 */ 892 template <ssize_t Dims = -1> detail::unchecked_reference<T, Dims> unchecked() const & { 893 return array::unchecked<T, Dims>(); 894 } 895 896 /// Ensure that the argument is a NumPy array of the correct dtype (and if not, try to convert 897 /// it). In case of an error, nullptr is returned and the Python error is cleared. 898 static array_t ensure(handle h) { 899 auto result = reinterpret_steal<array_t>(raw_array_t(h.ptr())); 900 if (!result) 901 PyErr_Clear(); 902 return result; 903 } 904 905 static bool check_(handle h) { 906 const auto &api = detail::npy_api::get(); 907 return api.PyArray_Check_(h.ptr()) 908 && api.PyArray_EquivTypes_(detail::array_proxy(h.ptr())->descr, dtype::of<T>().ptr()); 909 } 910 911protected: 912 /// Create array from any object -- always returns a new reference 913 static PyObject *raw_array_t(PyObject *ptr) { 914 if (ptr == nullptr) { 915 PyErr_SetString(PyExc_ValueError, "cannot create a pybind11::array_t from a nullptr"); 916 return nullptr; 917 } 918 return detail::npy_api::get().PyArray_FromAny_( 919 ptr, dtype::of<T>().release().ptr(), 0, 0, 920 detail::npy_api::NPY_ARRAY_ENSUREARRAY_ | ExtraFlags, nullptr); 921 } 922}; 923 924template <typename T> 925struct format_descriptor<T, detail::enable_if_t<detail::is_pod_struct<T>::value>> { 926 static std::string format() { 927 return detail::npy_format_descriptor<typename std::remove_cv<T>::type>::format(); 928 } 929}; 930 931template <size_t N> struct format_descriptor<char[N]> { 932 static std::string format() { return std::to_string(N) + "s"; } 933}; 934template <size_t N> struct format_descriptor<std::array<char, N>> { 935 static std::string format() { return std::to_string(N) + "s"; } 936}; 937 938template <typename T> 939struct format_descriptor<T, detail::enable_if_t<std::is_enum<T>::value>> { 940 static std::string format() { 941 return format_descriptor< 942 typename std::remove_cv<typename std::underlying_type<T>::type>::type>::format(); 943 } 944}; 945 946template <typename T> 947struct format_descriptor<T, detail::enable_if_t<detail::array_info<T>::is_array>> { 948 static std::string format() { 949 using detail::_; 950 PYBIND11_DESCR extents = _("(") + detail::array_info<T>::extents() + _(")"); 951 return extents.text() + format_descriptor<detail::remove_all_extents_t<T>>::format(); 952 } 953}; 954 955NAMESPACE_BEGIN(detail) 956template <typename T, int ExtraFlags> 957struct pyobject_caster<array_t<T, ExtraFlags>> { 958 using type = array_t<T, ExtraFlags>; 959 960 bool load(handle src, bool convert) { 961 if (!convert && !type::check_(src)) 962 return false; 963 value = type::ensure(src); 964 return static_cast<bool>(value); 965 } 966 967 static handle cast(const handle &src, return_value_policy /* policy */, handle /* parent */) { 968 return src.inc_ref(); 969 } 970 PYBIND11_TYPE_CASTER(type, handle_type_name<type>::name()); 971}; 972 973template <typename T> 974struct compare_buffer_info<T, detail::enable_if_t<detail::is_pod_struct<T>::value>> { 975 static bool compare(const buffer_info& b) { 976 return npy_api::get().PyArray_EquivTypes_(dtype::of<T>().ptr(), dtype(b).ptr()); 977 } 978}; 979 980template <typename T> struct npy_format_descriptor<T, enable_if_t<satisfies_any_of<T, std::is_arithmetic, is_complex>::value>> { 981private: 982 // NB: the order here must match the one in common.h 983 constexpr static const int values[15] = { 984 npy_api::NPY_BOOL_, 985 npy_api::NPY_BYTE_, npy_api::NPY_UBYTE_, npy_api::NPY_SHORT_, npy_api::NPY_USHORT_, 986 npy_api::NPY_INT_, npy_api::NPY_UINT_, npy_api::NPY_LONGLONG_, npy_api::NPY_ULONGLONG_, 987 npy_api::NPY_FLOAT_, npy_api::NPY_DOUBLE_, npy_api::NPY_LONGDOUBLE_, 988 npy_api::NPY_CFLOAT_, npy_api::NPY_CDOUBLE_, npy_api::NPY_CLONGDOUBLE_ 989 }; 990 991public: 992 static constexpr int value = values[detail::is_fmt_numeric<T>::index]; 993 994 static pybind11::dtype dtype() { 995 if (auto ptr = npy_api::get().PyArray_DescrFromType_(value)) 996 return reinterpret_borrow<pybind11::dtype>(ptr); 997 pybind11_fail("Unsupported buffer format!"); 998 } 999 template <typename T2 = T, enable_if_t<std::is_integral<T2>::value, int> = 0> 1000 static PYBIND11_DESCR name() { 1001 return _<std::is_same<T, bool>::value>(_("bool"), 1002 _<std::is_signed<T>::value>("int", "uint") + _<sizeof(T)*8>()); 1003 } 1004 template <typename T2 = T, enable_if_t<std::is_floating_point<T2>::value, int> = 0> 1005 static PYBIND11_DESCR name() { 1006 return _<std::is_same<T, float>::value || std::is_same<T, double>::value>( 1007 _("float") + _<sizeof(T)*8>(), _("longdouble")); 1008 } 1009 template <typename T2 = T, enable_if_t<is_complex<T2>::value, int> = 0> 1010 static PYBIND11_DESCR name() { 1011 return _<std::is_same<typename T2::value_type, float>::value || std::is_same<typename T2::value_type, double>::value>( 1012 _("complex") + _<sizeof(typename T2::value_type)*16>(), _("longcomplex")); 1013 } 1014}; 1015 1016#define PYBIND11_DECL_CHAR_FMT \ 1017 static PYBIND11_DESCR name() { return _("S") + _<N>(); } \ 1018 static pybind11::dtype dtype() { return pybind11::dtype(std::string("S") + std::to_string(N)); } 1019template <size_t N> struct npy_format_descriptor<char[N]> { PYBIND11_DECL_CHAR_FMT }; 1020template <size_t N> struct npy_format_descriptor<std::array<char, N>> { PYBIND11_DECL_CHAR_FMT }; 1021#undef PYBIND11_DECL_CHAR_FMT 1022 1023template<typename T> struct npy_format_descriptor<T, enable_if_t<array_info<T>::is_array>> { 1024private: 1025 using base_descr = npy_format_descriptor<typename array_info<T>::type>; 1026public: 1027 static_assert(!array_info<T>::is_empty, "Zero-sized arrays are not supported"); 1028 1029 static PYBIND11_DESCR name() { return _("(") + array_info<T>::extents() + _(")") + base_descr::name(); } 1030 static pybind11::dtype dtype() { 1031 list shape; 1032 array_info<T>::append_extents(shape); 1033 return pybind11::dtype::from_args(pybind11::make_tuple(base_descr::dtype(), shape)); 1034 } 1035}; 1036 1037template<typename T> struct npy_format_descriptor<T, enable_if_t<std::is_enum<T>::value>> { 1038private: 1039 using base_descr = npy_format_descriptor<typename std::underlying_type<T>::type>; 1040public: 1041 static PYBIND11_DESCR name() { return base_descr::name(); } 1042 static pybind11::dtype dtype() { return base_descr::dtype(); } 1043}; 1044 1045struct field_descriptor { 1046 const char *name; 1047 ssize_t offset; 1048 ssize_t size; 1049 std::string format; 1050 dtype descr; 1051}; 1052 1053inline PYBIND11_NOINLINE void register_structured_dtype( 1054 const std::initializer_list<field_descriptor>& fields, 1055 const std::type_info& tinfo, ssize_t itemsize, 1056 bool (*direct_converter)(PyObject *, void *&)) { 1057 1058 auto& numpy_internals = get_numpy_internals(); 1059 if (numpy_internals.get_type_info(tinfo, false)) 1060 pybind11_fail("NumPy: dtype is already registered"); 1061 1062 list names, formats, offsets; 1063 for (auto field : fields) { 1064 if (!field.descr) 1065 pybind11_fail(std::string("NumPy: unsupported field dtype: `") + 1066 field.name + "` @ " + tinfo.name()); 1067 names.append(PYBIND11_STR_TYPE(field.name)); 1068 formats.append(field.descr); 1069 offsets.append(pybind11::int_(field.offset)); 1070 } 1071 auto dtype_ptr = pybind11::dtype(names, formats, offsets, itemsize).release().ptr(); 1072 1073 // There is an existing bug in NumPy (as of v1.11): trailing bytes are 1074 // not encoded explicitly into the format string. This will supposedly 1075 // get fixed in v1.12; for further details, see these: 1076 // - https://github.com/numpy/numpy/issues/7797 1077 // - https://github.com/numpy/numpy/pull/7798 1078 // Because of this, we won't use numpy's logic to generate buffer format 1079 // strings and will just do it ourselves. 1080 std::vector<field_descriptor> ordered_fields(fields); 1081 std::sort(ordered_fields.begin(), ordered_fields.end(), 1082 [](const field_descriptor &a, const field_descriptor &b) { return a.offset < b.offset; }); 1083 ssize_t offset = 0; 1084 std::ostringstream oss; 1085 // mark the structure as unaligned with '^', because numpy and C++ don't 1086 // always agree about alignment (particularly for complex), and we're 1087 // explicitly listing all our padding. This depends on none of the fields 1088 // overriding the endianness. Putting the ^ in front of individual fields 1089 // isn't guaranteed to work due to https://github.com/numpy/numpy/issues/9049 1090 oss << "^T{"; 1091 for (auto& field : ordered_fields) { 1092 if (field.offset > offset) 1093 oss << (field.offset - offset) << 'x'; 1094 oss << field.format << ':' << field.name << ':'; 1095 offset = field.offset + field.size; 1096 } 1097 if (itemsize > offset) 1098 oss << (itemsize - offset) << 'x'; 1099 oss << '}'; 1100 auto format_str = oss.str(); 1101 1102 // Sanity check: verify that NumPy properly parses our buffer format string 1103 auto& api = npy_api::get(); 1104 auto arr = array(buffer_info(nullptr, itemsize, format_str, 1)); 1105 if (!api.PyArray_EquivTypes_(dtype_ptr, arr.dtype().ptr())) 1106 pybind11_fail("NumPy: invalid buffer descriptor!"); 1107 1108 auto tindex = std::type_index(tinfo); 1109 numpy_internals.registered_dtypes[tindex] = { dtype_ptr, format_str }; 1110 get_internals().direct_conversions[tindex].push_back(direct_converter); 1111} 1112 1113template <typename T, typename SFINAE> struct npy_format_descriptor { 1114 static_assert(is_pod_struct<T>::value, "Attempt to use a non-POD or unimplemented POD type as a numpy dtype"); 1115 1116 static PYBIND11_DESCR name() { return make_caster<T>::name(); } 1117 1118 static pybind11::dtype dtype() { 1119 return reinterpret_borrow<pybind11::dtype>(dtype_ptr()); 1120 } 1121 1122 static std::string format() { 1123 static auto format_str = get_numpy_internals().get_type_info<T>(true)->format_str; 1124 return format_str; 1125 } 1126 1127 static void register_dtype(const std::initializer_list<field_descriptor>& fields) { 1128 register_structured_dtype(fields, typeid(typename std::remove_cv<T>::type), 1129 sizeof(T), &direct_converter); 1130 } 1131 1132private: 1133 static PyObject* dtype_ptr() { 1134 static PyObject* ptr = get_numpy_internals().get_type_info<T>(true)->dtype_ptr; 1135 return ptr; 1136 } 1137 1138 static bool direct_converter(PyObject *obj, void*& value) { 1139 auto& api = npy_api::get(); 1140 if (!PyObject_TypeCheck(obj, api.PyVoidArrType_Type_)) 1141 return false; 1142 if (auto descr = reinterpret_steal<object>(api.PyArray_DescrFromScalar_(obj))) { 1143 if (api.PyArray_EquivTypes_(dtype_ptr(), descr.ptr())) { 1144 value = ((PyVoidScalarObject_Proxy *) obj)->obval; 1145 return true; 1146 } 1147 } 1148 return false; 1149 } 1150}; 1151 1152#ifdef __CLION_IDE__ // replace heavy macro with dummy code for the IDE (doesn't affect code) 1153# define PYBIND11_NUMPY_DTYPE(Type, ...) ((void)0) 1154# define PYBIND11_NUMPY_DTYPE_EX(Type, ...) ((void)0) 1155#else 1156 1157#define PYBIND11_FIELD_DESCRIPTOR_EX(T, Field, Name) \ 1158 ::pybind11::detail::field_descriptor { \ 1159 Name, offsetof(T, Field), sizeof(decltype(std::declval<T>().Field)), \ 1160 ::pybind11::format_descriptor<decltype(std::declval<T>().Field)>::format(), \ 1161 ::pybind11::detail::npy_format_descriptor<decltype(std::declval<T>().Field)>::dtype() \ 1162 } 1163 1164// Extract name, offset and format descriptor for a struct field 1165#define PYBIND11_FIELD_DESCRIPTOR(T, Field) PYBIND11_FIELD_DESCRIPTOR_EX(T, Field, #Field) 1166 1167// The main idea of this macro is borrowed from https://github.com/swansontec/map-macro 1168// (C) William Swanson, Paul Fultz 1169#define PYBIND11_EVAL0(...) __VA_ARGS__ 1170#define PYBIND11_EVAL1(...) PYBIND11_EVAL0 (PYBIND11_EVAL0 (PYBIND11_EVAL0 (__VA_ARGS__))) 1171#define PYBIND11_EVAL2(...) PYBIND11_EVAL1 (PYBIND11_EVAL1 (PYBIND11_EVAL1 (__VA_ARGS__))) 1172#define PYBIND11_EVAL3(...) PYBIND11_EVAL2 (PYBIND11_EVAL2 (PYBIND11_EVAL2 (__VA_ARGS__))) 1173#define PYBIND11_EVAL4(...) PYBIND11_EVAL3 (PYBIND11_EVAL3 (PYBIND11_EVAL3 (__VA_ARGS__))) 1174#define PYBIND11_EVAL(...) PYBIND11_EVAL4 (PYBIND11_EVAL4 (PYBIND11_EVAL4 (__VA_ARGS__))) 1175#define PYBIND11_MAP_END(...) 1176#define PYBIND11_MAP_OUT 1177#define PYBIND11_MAP_COMMA , 1178#define PYBIND11_MAP_GET_END() 0, PYBIND11_MAP_END 1179#define PYBIND11_MAP_NEXT0(test, next, ...) next PYBIND11_MAP_OUT 1180#define PYBIND11_MAP_NEXT1(test, next) PYBIND11_MAP_NEXT0 (test, next, 0) 1181#define PYBIND11_MAP_NEXT(test, next) PYBIND11_MAP_NEXT1 (PYBIND11_MAP_GET_END test, next) 1182#ifdef _MSC_VER // MSVC is not as eager to expand macros, hence this workaround 1183#define PYBIND11_MAP_LIST_NEXT1(test, next) \ 1184 PYBIND11_EVAL0 (PYBIND11_MAP_NEXT0 (test, PYBIND11_MAP_COMMA next, 0)) 1185#else 1186#define PYBIND11_MAP_LIST_NEXT1(test, next) \ 1187 PYBIND11_MAP_NEXT0 (test, PYBIND11_MAP_COMMA next, 0) 1188#endif 1189#define PYBIND11_MAP_LIST_NEXT(test, next) \ 1190 PYBIND11_MAP_LIST_NEXT1 (PYBIND11_MAP_GET_END test, next) 1191#define PYBIND11_MAP_LIST0(f, t, x, peek, ...) \ 1192 f(t, x) PYBIND11_MAP_LIST_NEXT (peek, PYBIND11_MAP_LIST1) (f, t, peek, __VA_ARGS__) 1193#define PYBIND11_MAP_LIST1(f, t, x, peek, ...) \ 1194 f(t, x) PYBIND11_MAP_LIST_NEXT (peek, PYBIND11_MAP_LIST0) (f, t, peek, __VA_ARGS__) 1195// PYBIND11_MAP_LIST(f, t, a1, a2, ...) expands to f(t, a1), f(t, a2), ... 1196#define PYBIND11_MAP_LIST(f, t, ...) \ 1197 PYBIND11_EVAL (PYBIND11_MAP_LIST1 (f, t, __VA_ARGS__, (), 0)) 1198 1199#define PYBIND11_NUMPY_DTYPE(Type, ...) \ 1200 ::pybind11::detail::npy_format_descriptor<Type>::register_dtype \ 1201 ({PYBIND11_MAP_LIST (PYBIND11_FIELD_DESCRIPTOR, Type, __VA_ARGS__)}) 1202 1203#ifdef _MSC_VER 1204#define PYBIND11_MAP2_LIST_NEXT1(test, next) \ 1205 PYBIND11_EVAL0 (PYBIND11_MAP_NEXT0 (test, PYBIND11_MAP_COMMA next, 0)) 1206#else 1207#define PYBIND11_MAP2_LIST_NEXT1(test, next) \ 1208 PYBIND11_MAP_NEXT0 (test, PYBIND11_MAP_COMMA next, 0) 1209#endif 1210#define PYBIND11_MAP2_LIST_NEXT(test, next) \ 1211 PYBIND11_MAP2_LIST_NEXT1 (PYBIND11_MAP_GET_END test, next) 1212#define PYBIND11_MAP2_LIST0(f, t, x1, x2, peek, ...) \ 1213 f(t, x1, x2) PYBIND11_MAP2_LIST_NEXT (peek, PYBIND11_MAP2_LIST1) (f, t, peek, __VA_ARGS__) 1214#define PYBIND11_MAP2_LIST1(f, t, x1, x2, peek, ...) \ 1215 f(t, x1, x2) PYBIND11_MAP2_LIST_NEXT (peek, PYBIND11_MAP2_LIST0) (f, t, peek, __VA_ARGS__) 1216// PYBIND11_MAP2_LIST(f, t, a1, a2, ...) expands to f(t, a1, a2), f(t, a3, a4), ... 1217#define PYBIND11_MAP2_LIST(f, t, ...) \ 1218 PYBIND11_EVAL (PYBIND11_MAP2_LIST1 (f, t, __VA_ARGS__, (), 0)) 1219 1220#define PYBIND11_NUMPY_DTYPE_EX(Type, ...) \ 1221 ::pybind11::detail::npy_format_descriptor<Type>::register_dtype \ 1222 ({PYBIND11_MAP2_LIST (PYBIND11_FIELD_DESCRIPTOR_EX, Type, __VA_ARGS__)}) 1223 1224#endif // __CLION_IDE__ 1225 1226template <class T> 1227using array_iterator = typename std::add_pointer<T>::type; 1228 1229template <class T> 1230array_iterator<T> array_begin(const buffer_info& buffer) { 1231 return array_iterator<T>(reinterpret_cast<T*>(buffer.ptr)); 1232} 1233 1234template <class T> 1235array_iterator<T> array_end(const buffer_info& buffer) { 1236 return array_iterator<T>(reinterpret_cast<T*>(buffer.ptr) + buffer.size); 1237} 1238 1239class common_iterator { 1240public: 1241 using container_type = std::vector<ssize_t>; 1242 using value_type = container_type::value_type; 1243 using size_type = container_type::size_type; 1244 1245 common_iterator() : p_ptr(0), m_strides() {} 1246 1247 common_iterator(void* ptr, const container_type& strides, const container_type& shape) 1248 : p_ptr(reinterpret_cast<char*>(ptr)), m_strides(strides.size()) { 1249 m_strides.back() = static_cast<value_type>(strides.back()); 1250 for (size_type i = m_strides.size() - 1; i != 0; --i) { 1251 size_type j = i - 1; 1252 value_type s = static_cast<value_type>(shape[i]); 1253 m_strides[j] = strides[j] + m_strides[i] - strides[i] * s; 1254 } 1255 } 1256 1257 void increment(size_type dim) { 1258 p_ptr += m_strides[dim]; 1259 } 1260 1261 void* data() const { 1262 return p_ptr; 1263 } 1264 1265private: 1266 char* p_ptr; 1267 container_type m_strides; 1268}; 1269 1270template <size_t N> class multi_array_iterator { 1271public: 1272 using container_type = std::vector<ssize_t>; 1273 1274 multi_array_iterator(const std::array<buffer_info, N> &buffers, 1275 const container_type &shape) 1276 : m_shape(shape.size()), m_index(shape.size(), 0), 1277 m_common_iterator() { 1278 1279 // Manual copy to avoid conversion warning if using std::copy 1280 for (size_t i = 0; i < shape.size(); ++i) 1281 m_shape[i] = shape[i]; 1282 1283 container_type strides(shape.size()); 1284 for (size_t i = 0; i < N; ++i) 1285 init_common_iterator(buffers[i], shape, m_common_iterator[i], strides); 1286 } 1287 1288 multi_array_iterator& operator++() { 1289 for (size_t j = m_index.size(); j != 0; --j) { 1290 size_t i = j - 1; 1291 if (++m_index[i] != m_shape[i]) { 1292 increment_common_iterator(i); 1293 break; 1294 } else { 1295 m_index[i] = 0; 1296 } 1297 } 1298 return *this; 1299 } 1300 1301 template <size_t K, class T = void> T* data() const { 1302 return reinterpret_cast<T*>(m_common_iterator[K].data()); 1303 } 1304 1305private: 1306 1307 using common_iter = common_iterator; 1308 1309 void init_common_iterator(const buffer_info &buffer, 1310 const container_type &shape, 1311 common_iter &iterator, 1312 container_type &strides) { 1313 auto buffer_shape_iter = buffer.shape.rbegin(); 1314 auto buffer_strides_iter = buffer.strides.rbegin(); 1315 auto shape_iter = shape.rbegin(); 1316 auto strides_iter = strides.rbegin(); 1317 1318 while (buffer_shape_iter != buffer.shape.rend()) { 1319 if (*shape_iter == *buffer_shape_iter) 1320 *strides_iter = *buffer_strides_iter; 1321 else 1322 *strides_iter = 0; 1323 1324 ++buffer_shape_iter; 1325 ++buffer_strides_iter; 1326 ++shape_iter; 1327 ++strides_iter; 1328 } 1329 1330 std::fill(strides_iter, strides.rend(), 0); 1331 iterator = common_iter(buffer.ptr, strides, shape); 1332 } 1333 1334 void increment_common_iterator(size_t dim) { 1335 for (auto &iter : m_common_iterator) 1336 iter.increment(dim); 1337 } 1338 1339 container_type m_shape; 1340 container_type m_index; 1341 std::array<common_iter, N> m_common_iterator; 1342}; 1343 1344enum class broadcast_trivial { non_trivial, c_trivial, f_trivial }; 1345 1346// Populates the shape and number of dimensions for the set of buffers. Returns a broadcast_trivial 1347// enum value indicating whether the broadcast is "trivial"--that is, has each buffer being either a 1348// singleton or a full-size, C-contiguous (`c_trivial`) or Fortran-contiguous (`f_trivial`) storage 1349// buffer; returns `non_trivial` otherwise. 1350template <size_t N> 1351broadcast_trivial broadcast(const std::array<buffer_info, N> &buffers, ssize_t &ndim, std::vector<ssize_t> &shape) { 1352 ndim = std::accumulate(buffers.begin(), buffers.end(), ssize_t(0), [](ssize_t res, const buffer_info &buf) { 1353 return std::max(res, buf.ndim); 1354 }); 1355 1356 shape.clear(); 1357 shape.resize((size_t) ndim, 1); 1358 1359 // Figure out the output size, and make sure all input arrays conform (i.e. are either size 1 or 1360 // the full size). 1361 for (size_t i = 0; i < N; ++i) { 1362 auto res_iter = shape.rbegin(); 1363 auto end = buffers[i].shape.rend(); 1364 for (auto shape_iter = buffers[i].shape.rbegin(); shape_iter != end; ++shape_iter, ++res_iter) { 1365 const auto &dim_size_in = *shape_iter; 1366 auto &dim_size_out = *res_iter; 1367 1368 // Each input dimension can either be 1 or `n`, but `n` values must match across buffers 1369 if (dim_size_out == 1) 1370 dim_size_out = dim_size_in; 1371 else if (dim_size_in != 1 && dim_size_in != dim_size_out) 1372 pybind11_fail("pybind11::vectorize: incompatible size/dimension of inputs!"); 1373 } 1374 } 1375 1376 bool trivial_broadcast_c = true; 1377 bool trivial_broadcast_f = true; 1378 for (size_t i = 0; i < N && (trivial_broadcast_c || trivial_broadcast_f); ++i) { 1379 if (buffers[i].size == 1) 1380 continue; 1381 1382 // Require the same number of dimensions: 1383 if (buffers[i].ndim != ndim) 1384 return broadcast_trivial::non_trivial; 1385 1386 // Require all dimensions be full-size: 1387 if (!std::equal(buffers[i].shape.cbegin(), buffers[i].shape.cend(), shape.cbegin())) 1388 return broadcast_trivial::non_trivial; 1389 1390 // Check for C contiguity (but only if previous inputs were also C contiguous) 1391 if (trivial_broadcast_c) { 1392 ssize_t expect_stride = buffers[i].itemsize; 1393 auto end = buffers[i].shape.crend(); 1394 for (auto shape_iter = buffers[i].shape.crbegin(), stride_iter = buffers[i].strides.crbegin(); 1395 trivial_broadcast_c && shape_iter != end; ++shape_iter, ++stride_iter) { 1396 if (expect_stride == *stride_iter) 1397 expect_stride *= *shape_iter; 1398 else 1399 trivial_broadcast_c = false; 1400 } 1401 } 1402 1403 // Check for Fortran contiguity (if previous inputs were also F contiguous) 1404 if (trivial_broadcast_f) { 1405 ssize_t expect_stride = buffers[i].itemsize; 1406 auto end = buffers[i].shape.cend(); 1407 for (auto shape_iter = buffers[i].shape.cbegin(), stride_iter = buffers[i].strides.cbegin(); 1408 trivial_broadcast_f && shape_iter != end; ++shape_iter, ++stride_iter) { 1409 if (expect_stride == *stride_iter) 1410 expect_stride *= *shape_iter; 1411 else 1412 trivial_broadcast_f = false; 1413 } 1414 } 1415 } 1416 1417 return 1418 trivial_broadcast_c ? broadcast_trivial::c_trivial : 1419 trivial_broadcast_f ? broadcast_trivial::f_trivial : 1420 broadcast_trivial::non_trivial; 1421} 1422 1423template <typename T> 1424struct vectorize_arg { 1425 static_assert(!std::is_rvalue_reference<T>::value, "Functions with rvalue reference arguments cannot be vectorized"); 1426 // The wrapped function gets called with this type: 1427 using call_type = remove_reference_t<T>; 1428 // Is this a vectorized argument? 1429 static constexpr bool vectorize = 1430 satisfies_any_of<call_type, std::is_arithmetic, is_complex, std::is_pod>::value && 1431 satisfies_none_of<call_type, std::is_pointer, std::is_array, is_std_array, std::is_enum>::value && 1432 (!std::is_reference<T>::value || 1433 (std::is_lvalue_reference<T>::value && std::is_const<call_type>::value)); 1434 // Accept this type: an array for vectorized types, otherwise the type as-is: 1435 using type = conditional_t<vectorize, array_t<remove_cv_t<call_type>, array::forcecast>, T>; 1436}; 1437 1438template <typename Func, typename Return, typename... Args> 1439struct vectorize_helper { 1440private: 1441 static constexpr size_t N = sizeof...(Args); 1442 static constexpr size_t NVectorized = constexpr_sum(vectorize_arg<Args>::vectorize...); 1443 static_assert(NVectorized >= 1, 1444 "pybind11::vectorize(...) requires a function with at least one vectorizable argument"); 1445 1446public: 1447 template <typename T> 1448 explicit vectorize_helper(T &&f) : f(std::forward<T>(f)) { } 1449 1450 object operator()(typename vectorize_arg<Args>::type... args) { 1451 return run(args..., 1452 make_index_sequence<N>(), 1453 select_indices<vectorize_arg<Args>::vectorize...>(), 1454 make_index_sequence<NVectorized>()); 1455 } 1456 1457private: 1458 remove_reference_t<Func> f; 1459 1460 template <size_t Index> using param_n_t = typename pack_element<Index, typename vectorize_arg<Args>::call_type...>::type; 1461 1462 // Runs a vectorized function given arguments tuple and three index sequences: 1463 // - Index is the full set of 0 ... (N-1) argument indices; 1464 // - VIndex is the subset of argument indices with vectorized parameters, letting us access 1465 // vectorized arguments (anything not in this sequence is passed through) 1466 // - BIndex is a incremental sequence (beginning at 0) of the same size as VIndex, so that 1467 // we can store vectorized buffer_infos in an array (argument VIndex has its buffer at 1468 // index BIndex in the array). 1469 template <size_t... Index, size_t... VIndex, size_t... BIndex> object run( 1470 typename vectorize_arg<Args>::type &...args, 1471 index_sequence<Index...> i_seq, index_sequence<VIndex...> vi_seq, index_sequence<BIndex...> bi_seq) { 1472 1473 // Pointers to values the function was called with; the vectorized ones set here will start 1474 // out as array_t<T> pointers, but they will be changed them to T pointers before we make 1475 // call the wrapped function. Non-vectorized pointers are left as-is. 1476 std::array<void *, N> params{{ &args... }}; 1477 1478 // The array of `buffer_info`s of vectorized arguments: 1479 std::array<buffer_info, NVectorized> buffers{{ reinterpret_cast<array *>(params[VIndex])->request()... }}; 1480 1481 /* Determine dimensions parameters of output array */ 1482 ssize_t nd = 0; 1483 std::vector<ssize_t> shape(0); 1484 auto trivial = broadcast(buffers, nd, shape); 1485 size_t ndim = (size_t) nd; 1486 1487 size_t size = std::accumulate(shape.begin(), shape.end(), (size_t) 1, std::multiplies<size_t>()); 1488 1489 // If all arguments are 0-dimension arrays (i.e. single values) return a plain value (i.e. 1490 // not wrapped in an array). 1491 if (size == 1 && ndim == 0) { 1492 PYBIND11_EXPAND_SIDE_EFFECTS(params[VIndex] = buffers[BIndex].ptr); 1493 return cast(f(*reinterpret_cast<param_n_t<Index> *>(params[Index])...)); 1494 } 1495 1496 array_t<Return> result; 1497 if (trivial == broadcast_trivial::f_trivial) result = array_t<Return, array::f_style>(shape); 1498 else result = array_t<Return>(shape); 1499 1500 if (size == 0) return result; 1501 1502 /* Call the function */ 1503 if (trivial == broadcast_trivial::non_trivial) 1504 apply_broadcast(buffers, params, result, i_seq, vi_seq, bi_seq); 1505 else 1506 apply_trivial(buffers, params, result.mutable_data(), size, i_seq, vi_seq, bi_seq); 1507 1508 return result; 1509 } 1510 1511 template <size_t... Index, size_t... VIndex, size_t... BIndex> 1512 void apply_trivial(std::array<buffer_info, NVectorized> &buffers, 1513 std::array<void *, N> ¶ms, 1514 Return *out, 1515 size_t size, 1516 index_sequence<Index...>, index_sequence<VIndex...>, index_sequence<BIndex...>) { 1517 1518 // Initialize an array of mutable byte references and sizes with references set to the 1519 // appropriate pointer in `params`; as we iterate, we'll increment each pointer by its size 1520 // (except for singletons, which get an increment of 0). 1521 std::array<std::pair<unsigned char *&, const size_t>, NVectorized> vecparams{{ 1522 std::pair<unsigned char *&, const size_t>( 1523 reinterpret_cast<unsigned char *&>(params[VIndex] = buffers[BIndex].ptr), 1524 buffers[BIndex].size == 1 ? 0 : sizeof(param_n_t<VIndex>) 1525 )... 1526 }}; 1527 1528 for (size_t i = 0; i < size; ++i) { 1529 out[i] = f(*reinterpret_cast<param_n_t<Index> *>(params[Index])...); 1530 for (auto &x : vecparams) x.first += x.second; 1531 } 1532 } 1533 1534 template <size_t... Index, size_t... VIndex, size_t... BIndex> 1535 void apply_broadcast(std::array<buffer_info, NVectorized> &buffers, 1536 std::array<void *, N> ¶ms, 1537 array_t<Return> &output_array, 1538 index_sequence<Index...>, index_sequence<VIndex...>, index_sequence<BIndex...>) { 1539 1540 buffer_info output = output_array.request(); 1541 multi_array_iterator<NVectorized> input_iter(buffers, output.shape); 1542 1543 for (array_iterator<Return> iter = array_begin<Return>(output), end = array_end<Return>(output); 1544 iter != end; 1545 ++iter, ++input_iter) { 1546 PYBIND11_EXPAND_SIDE_EFFECTS(( 1547 params[VIndex] = input_iter.template data<BIndex>() 1548 )); 1549 *iter = f(*reinterpret_cast<param_n_t<Index> *>(std::get<Index>(params))...); 1550 } 1551 } 1552}; 1553 1554template <typename Func, typename Return, typename... Args> 1555vectorize_helper<Func, Return, Args...> 1556vectorize_extractor(const Func &f, Return (*) (Args ...)) { 1557 return detail::vectorize_helper<Func, Return, Args...>(f); 1558} 1559 1560template <typename T, int Flags> struct handle_type_name<array_t<T, Flags>> { 1561 static PYBIND11_DESCR name() { 1562 return _("numpy.ndarray[") + npy_format_descriptor<T>::name() + _("]"); 1563 } 1564}; 1565 1566NAMESPACE_END(detail) 1567 1568// Vanilla pointer vectorizer: 1569template <typename Return, typename... Args> 1570detail::vectorize_helper<Return (*)(Args...), Return, Args...> 1571vectorize(Return (*f) (Args ...)) { 1572 return detail::vectorize_helper<Return (*)(Args...), Return, Args...>(f); 1573} 1574 1575// lambda vectorizer: 1576template <typename Func, detail::enable_if_t<detail::is_lambda<Func>::value, int> = 0> 1577auto vectorize(Func &&f) -> decltype( 1578 detail::vectorize_extractor(std::forward<Func>(f), (detail::function_signature_t<Func> *) nullptr)) { 1579 return detail::vectorize_extractor(std::forward<Func>(f), (detail::function_signature_t<Func> *) nullptr); 1580} 1581 1582// Vectorize a class method (non-const): 1583template <typename Return, typename Class, typename... Args, 1584 typename Helper = detail::vectorize_helper<decltype(std::mem_fn(std::declval<Return (Class::*)(Args...)>())), Return, Class *, Args...>> 1585Helper vectorize(Return (Class::*f)(Args...)) { 1586 return Helper(std::mem_fn(f)); 1587} 1588 1589// Vectorize a class method (non-const): 1590template <typename Return, typename Class, typename... Args, 1591 typename Helper = detail::vectorize_helper<decltype(std::mem_fn(std::declval<Return (Class::*)(Args...) const>())), Return, const Class *, Args...>> 1592Helper vectorize(Return (Class::*f)(Args...) const) { 1593 return Helper(std::mem_fn(f)); 1594} 1595 1596NAMESPACE_END(PYBIND11_NAMESPACE) 1597 1598#if defined(_MSC_VER) 1599#pragma warning(pop) 1600#endif 1601