pybind11.h revision 11986:c12e4625ab56
1/* 2 pybind11/pybind11.h: Main header file of the C++11 python 3 binding generator library 4 5 Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch> 6 7 All rights reserved. Use of this source code is governed by a 8 BSD-style license that can be found in the LICENSE file. 9*/ 10 11#pragma once 12 13#if defined(_MSC_VER) 14# pragma warning(push) 15# pragma warning(disable: 4100) // warning C4100: Unreferenced formal parameter 16# pragma warning(disable: 4127) // warning C4127: Conditional expression is constant 17# pragma warning(disable: 4512) // warning C4512: Assignment operator was implicitly defined as deleted 18# pragma warning(disable: 4800) // warning C4800: 'int': forcing value to bool 'true' or 'false' (performance warning) 19# pragma warning(disable: 4996) // warning C4996: The POSIX name for this item is deprecated. Instead, use the ISO C and C++ conformant name 20# pragma warning(disable: 4702) // warning C4702: unreachable code 21# pragma warning(disable: 4522) // warning C4522: multiple assignment operators specified 22#elif defined(__INTEL_COMPILER) 23# pragma warning(push) 24# pragma warning(disable: 186) // pointless comparison of unsigned integer with zero 25# pragma warning(disable: 1334) // the "template" keyword used for syntactic disambiguation may only be used within a template 26# pragma warning(disable: 2196) // warning #2196: routine is both "inline" and "noinline" 27#elif defined(__GNUG__) && !defined(__clang__) 28# pragma GCC diagnostic push 29# pragma GCC diagnostic ignored "-Wunused-but-set-parameter" 30# pragma GCC diagnostic ignored "-Wunused-but-set-variable" 31# pragma GCC diagnostic ignored "-Wmissing-field-initializers" 32# pragma GCC diagnostic ignored "-Wstrict-aliasing" 33# pragma GCC diagnostic ignored "-Wattributes" 34#endif 35 36#include "attr.h" 37#include "options.h" 38 39NAMESPACE_BEGIN(pybind11) 40 41/// Wraps an arbitrary C++ function/method/lambda function/.. into a callable Python object 42class cpp_function : public function { 43public: 44 cpp_function() { } 45 46 /// Construct a cpp_function from a vanilla function pointer 47 template <typename Return, typename... Args, typename... Extra> 48 cpp_function(Return (*f)(Args...), const Extra&... extra) { 49 initialize(f, f, extra...); 50 } 51 52 /// Construct a cpp_function from a lambda function (possibly with internal state) 53 template <typename Func, typename... Extra> cpp_function(Func &&f, const Extra&... extra) { 54 initialize(std::forward<Func>(f), 55 (typename detail::remove_class<decltype( 56 &std::remove_reference<Func>::type::operator())>::type *) nullptr, extra...); 57 } 58 59 /// Construct a cpp_function from a class method (non-const) 60 template <typename Return, typename Class, typename... Arg, typename... Extra> 61 cpp_function(Return (Class::*f)(Arg...), const Extra&... extra) { 62 initialize([f](Class *c, Arg... args) -> Return { return (c->*f)(args...); }, 63 (Return (*) (Class *, Arg...)) nullptr, extra...); 64 } 65 66 /// Construct a cpp_function from a class method (const) 67 template <typename Return, typename Class, typename... Arg, typename... Extra> 68 cpp_function(Return (Class::*f)(Arg...) const, const Extra&... extra) { 69 initialize([f](const Class *c, Arg... args) -> Return { return (c->*f)(args...); }, 70 (Return (*)(const Class *, Arg ...)) nullptr, extra...); 71 } 72 73 /// Return the function name 74 object name() const { return attr("__name__"); } 75 76protected: 77 /// Space optimization: don't inline this frequently instantiated fragment 78 PYBIND11_NOINLINE detail::function_record *make_function_record() { 79 return new detail::function_record(); 80 } 81 82 /// Special internal constructor for functors, lambda functions, etc. 83 template <typename Func, typename Return, typename... Args, typename... Extra> 84 void initialize(Func &&f, Return (*)(Args...), const Extra&... extra) { 85 static_assert(detail::expected_num_args<Extra...>(sizeof...(Args)), 86 "The number of named arguments does not match the function signature"); 87 88 struct capture { typename std::remove_reference<Func>::type f; }; 89 90 /* Store the function including any extra state it might have (e.g. a lambda capture object) */ 91 auto rec = make_function_record(); 92 93 /* Store the capture object directly in the function record if there is enough space */ 94 if (sizeof(capture) <= sizeof(rec->data)) { 95 /* Without these pragmas, GCC warns that there might not be 96 enough space to use the placement new operator. However, the 97 'if' statement above ensures that this is the case. */ 98#if defined(__GNUG__) && !defined(__clang__) && __GNUC__ >= 6 99# pragma GCC diagnostic push 100# pragma GCC diagnostic ignored "-Wplacement-new" 101#endif 102 new ((capture *) &rec->data) capture { std::forward<Func>(f) }; 103#if defined(__GNUG__) && !defined(__clang__) && __GNUC__ >= 6 104# pragma GCC diagnostic pop 105#endif 106 if (!std::is_trivially_destructible<Func>::value) 107 rec->free_data = [](detail::function_record *r) { ((capture *) &r->data)->~capture(); }; 108 } else { 109 rec->data[0] = new capture { std::forward<Func>(f) }; 110 rec->free_data = [](detail::function_record *r) { delete ((capture *) r->data[0]); }; 111 } 112 113 /* Type casters for the function arguments and return value */ 114 using cast_in = detail::argument_loader<Args...>; 115 using cast_out = detail::make_caster< 116 detail::conditional_t<std::is_void<Return>::value, detail::void_type, Return> 117 >; 118 119 /* Dispatch code which converts function arguments and performs the actual function call */ 120 rec->impl = [](detail::function_record *rec, handle args, handle kwargs, handle parent) -> handle { 121 cast_in args_converter; 122 123 /* Try to cast the function arguments into the C++ domain */ 124 if (!args_converter.load_args(args, kwargs, true)) 125 return PYBIND11_TRY_NEXT_OVERLOAD; 126 127 /* Invoke call policy pre-call hook */ 128 detail::process_attributes<Extra...>::precall(args); 129 130 /* Get a pointer to the capture object */ 131 capture *cap = (capture *) (sizeof(capture) <= sizeof(rec->data) 132 ? &rec->data : rec->data[0]); 133 134 /* Override policy for rvalues -- always move */ 135 constexpr auto is_rvalue = !std::is_pointer<Return>::value 136 && !std::is_lvalue_reference<Return>::value; 137 const auto policy = is_rvalue ? return_value_policy::move : rec->policy; 138 139 /* Perform the function call */ 140 handle result = cast_out::cast(args_converter.template call<Return>(cap->f), 141 policy, parent); 142 143 /* Invoke call policy post-call hook */ 144 detail::process_attributes<Extra...>::postcall(args, result); 145 146 return result; 147 }; 148 149 /* Process any user-provided function attributes */ 150 detail::process_attributes<Extra...>::init(extra..., rec); 151 152 /* Generate a readable signature describing the function's arguments and return value types */ 153 using detail::descr; using detail::_; 154 PYBIND11_DESCR signature = _("(") + cast_in::arg_names() + _(") -> ") + cast_out::name(); 155 156 /* Register the function with Python from generic (non-templated) code */ 157 initialize_generic(rec, signature.text(), signature.types(), sizeof...(Args)); 158 159 if (cast_in::has_args) rec->has_args = true; 160 if (cast_in::has_kwargs) rec->has_kwargs = true; 161 162 /* Stash some additional information used by an important optimization in 'functional.h' */ 163 using FunctionType = Return (*)(Args...); 164 constexpr bool is_function_ptr = 165 std::is_convertible<Func, FunctionType>::value && 166 sizeof(capture) == sizeof(void *); 167 if (is_function_ptr) { 168 rec->is_stateless = true; 169 rec->data[1] = (void *) &typeid(FunctionType); 170 } 171 } 172 173 /// Register a function call with Python (generic non-templated code goes here) 174 void initialize_generic(detail::function_record *rec, const char *text, 175 const std::type_info *const *types, size_t args) { 176 177 /* Create copies of all referenced C-style strings */ 178 rec->name = strdup(rec->name ? rec->name : ""); 179 if (rec->doc) rec->doc = strdup(rec->doc); 180 for (auto &a: rec->args) { 181 if (a.name) 182 a.name = strdup(a.name); 183 if (a.descr) 184 a.descr = strdup(a.descr); 185 else if (a.value) 186 a.descr = strdup(a.value.attr("__repr__")().cast<std::string>().c_str()); 187 } 188 189 /* Generate a proper function signature */ 190 std::string signature; 191 size_t type_depth = 0, char_index = 0, type_index = 0, arg_index = 0; 192 while (true) { 193 char c = text[char_index++]; 194 if (c == '\0') 195 break; 196 197 if (c == '{') { 198 // Write arg name for everything except *args, **kwargs and return type. 199 if (type_depth == 0 && text[char_index] != '*' && arg_index < args) { 200 if (!rec->args.empty()) { 201 signature += rec->args[arg_index].name; 202 } else if (arg_index == 0 && rec->is_method) { 203 signature += "self"; 204 } else { 205 signature += "arg" + std::to_string(arg_index - (rec->is_method ? 1 : 0)); 206 } 207 signature += ": "; 208 } 209 ++type_depth; 210 } else if (c == '}') { 211 --type_depth; 212 if (type_depth == 0) { 213 if (arg_index < rec->args.size() && rec->args[arg_index].descr) { 214 signature += "="; 215 signature += rec->args[arg_index].descr; 216 } 217 arg_index++; 218 } 219 } else if (c == '%') { 220 const std::type_info *t = types[type_index++]; 221 if (!t) 222 pybind11_fail("Internal error while parsing type signature (1)"); 223 if (auto tinfo = detail::get_type_info(*t)) { 224 signature += tinfo->type->tp_name; 225 } else { 226 std::string tname(t->name()); 227 detail::clean_type_id(tname); 228 signature += tname; 229 } 230 } else { 231 signature += c; 232 } 233 } 234 if (type_depth != 0 || types[type_index] != nullptr) 235 pybind11_fail("Internal error while parsing type signature (2)"); 236 237 #if !defined(PYBIND11_CPP14) 238 delete[] types; 239 delete[] text; 240 #endif 241 242#if PY_MAJOR_VERSION < 3 243 if (strcmp(rec->name, "__next__") == 0) { 244 std::free(rec->name); 245 rec->name = strdup("next"); 246 } else if (strcmp(rec->name, "__bool__") == 0) { 247 std::free(rec->name); 248 rec->name = strdup("__nonzero__"); 249 } 250#endif 251 rec->signature = strdup(signature.c_str()); 252 rec->args.shrink_to_fit(); 253 rec->is_constructor = !strcmp(rec->name, "__init__") || !strcmp(rec->name, "__setstate__"); 254 rec->nargs = (uint16_t) args; 255 256#if PY_MAJOR_VERSION < 3 257 if (rec->sibling && PyMethod_Check(rec->sibling.ptr())) 258 rec->sibling = PyMethod_GET_FUNCTION(rec->sibling.ptr()); 259#endif 260 261 detail::function_record *chain = nullptr, *chain_start = rec; 262 if (rec->sibling) { 263 if (PyCFunction_Check(rec->sibling.ptr())) { 264 auto rec_capsule = reinterpret_borrow<capsule>(PyCFunction_GetSelf(rec->sibling.ptr())); 265 chain = (detail::function_record *) rec_capsule; 266 /* Never append a method to an overload chain of a parent class; 267 instead, hide the parent's overloads in this case */ 268 if (chain->scope != rec->scope) 269 chain = nullptr; 270 } 271 // Don't trigger for things like the default __init__, which are wrapper_descriptors that we are intentionally replacing 272 else if (!rec->sibling.is_none() && rec->name[0] != '_') 273 pybind11_fail("Cannot overload existing non-function object \"" + std::string(rec->name) + 274 "\" with a function of the same name"); 275 } 276 277 if (!chain) { 278 /* No existing overload was found, create a new function object */ 279 rec->def = new PyMethodDef(); 280 memset(rec->def, 0, sizeof(PyMethodDef)); 281 rec->def->ml_name = rec->name; 282 rec->def->ml_meth = reinterpret_cast<PyCFunction>(*dispatcher); 283 rec->def->ml_flags = METH_VARARGS | METH_KEYWORDS; 284 285 capsule rec_capsule(rec, [](PyObject *o) { 286 destruct((detail::function_record *) PyCapsule_GetPointer(o, nullptr)); 287 }); 288 289 object scope_module; 290 if (rec->scope) { 291 if (hasattr(rec->scope, "__module__")) { 292 scope_module = rec->scope.attr("__module__"); 293 } else if (hasattr(rec->scope, "__name__")) { 294 scope_module = rec->scope.attr("__name__"); 295 } 296 } 297 298 m_ptr = PyCFunction_NewEx(rec->def, rec_capsule.ptr(), scope_module.ptr()); 299 if (!m_ptr) 300 pybind11_fail("cpp_function::cpp_function(): Could not allocate function object"); 301 } else { 302 /* Append at the end of the overload chain */ 303 m_ptr = rec->sibling.ptr(); 304 inc_ref(); 305 chain_start = chain; 306 while (chain->next) 307 chain = chain->next; 308 chain->next = rec; 309 } 310 311 std::string signatures; 312 int index = 0; 313 /* Create a nice pydoc rec including all signatures and 314 docstrings of the functions in the overload chain */ 315 if (chain && options::show_function_signatures()) { 316 // First a generic signature 317 signatures += rec->name; 318 signatures += "(*args, **kwargs)\n"; 319 signatures += "Overloaded function.\n\n"; 320 } 321 // Then specific overload signatures 322 for (auto it = chain_start; it != nullptr; it = it->next) { 323 if (options::show_function_signatures()) { 324 if (chain) 325 signatures += std::to_string(++index) + ". "; 326 signatures += rec->name; 327 signatures += it->signature; 328 signatures += "\n"; 329 } 330 if (it->doc && strlen(it->doc) > 0 && options::show_user_defined_docstrings()) { 331 if (options::show_function_signatures()) signatures += "\n"; 332 signatures += it->doc; 333 if (options::show_function_signatures()) signatures += "\n"; 334 } 335 if (it->next) 336 signatures += "\n"; 337 } 338 339 /* Install docstring */ 340 PyCFunctionObject *func = (PyCFunctionObject *) m_ptr; 341 if (func->m_ml->ml_doc) 342 std::free((char *) func->m_ml->ml_doc); 343 func->m_ml->ml_doc = strdup(signatures.c_str()); 344 345 if (rec->is_method) { 346 m_ptr = PYBIND11_INSTANCE_METHOD_NEW(m_ptr, rec->scope.ptr()); 347 if (!m_ptr) 348 pybind11_fail("cpp_function::cpp_function(): Could not allocate instance method object"); 349 Py_DECREF(func); 350 } 351 } 352 353 /// When a cpp_function is GCed, release any memory allocated by pybind11 354 static void destruct(detail::function_record *rec) { 355 while (rec) { 356 detail::function_record *next = rec->next; 357 if (rec->free_data) 358 rec->free_data(rec); 359 std::free((char *) rec->name); 360 std::free((char *) rec->doc); 361 std::free((char *) rec->signature); 362 for (auto &arg: rec->args) { 363 std::free((char *) arg.name); 364 std::free((char *) arg.descr); 365 arg.value.dec_ref(); 366 } 367 if (rec->def) { 368 std::free((char *) rec->def->ml_doc); 369 delete rec->def; 370 } 371 delete rec; 372 rec = next; 373 } 374 } 375 376 /// Main dispatch logic for calls to functions bound using pybind11 377 static PyObject *dispatcher(PyObject *self, PyObject *args, PyObject *kwargs) { 378 /* Iterator over the list of potentially admissible overloads */ 379 detail::function_record *overloads = (detail::function_record *) PyCapsule_GetPointer(self, nullptr), 380 *it = overloads; 381 382 /* Need to know how many arguments + keyword arguments there are to pick the right overload */ 383 size_t nargs = (size_t) PyTuple_GET_SIZE(args), 384 nkwargs = kwargs ? (size_t) PyDict_Size(kwargs) : 0; 385 386 handle parent = nargs > 0 ? PyTuple_GET_ITEM(args, 0) : nullptr, 387 result = PYBIND11_TRY_NEXT_OVERLOAD; 388 try { 389 for (; it != nullptr; it = it->next) { 390 auto args_ = reinterpret_borrow<tuple>(args); 391 size_t kwargs_consumed = 0; 392 393 /* For each overload: 394 1. If the required list of arguments is longer than the 395 actually provided amount, create a copy of the argument 396 list and fill in any available keyword/default arguments. 397 2. Ensure that all keyword arguments were "consumed" 398 3. Call the function call dispatcher (function_record::impl) 399 */ 400 size_t nargs_ = nargs; 401 if (nargs < it->args.size()) { 402 nargs_ = it->args.size(); 403 args_ = tuple(nargs_); 404 for (size_t i = 0; i < nargs; ++i) { 405 handle item = PyTuple_GET_ITEM(args, i); 406 PyTuple_SET_ITEM(args_.ptr(), i, item.inc_ref().ptr()); 407 } 408 409 int arg_ctr = 0; 410 for (auto const &it2 : it->args) { 411 int index = arg_ctr++; 412 if (PyTuple_GET_ITEM(args_.ptr(), index)) 413 continue; 414 415 handle value; 416 if (kwargs) 417 value = PyDict_GetItemString(kwargs, it2.name); 418 419 if (value) 420 kwargs_consumed++; 421 else if (it2.value) 422 value = it2.value; 423 424 if (value) { 425 PyTuple_SET_ITEM(args_.ptr(), index, value.inc_ref().ptr()); 426 } else { 427 kwargs_consumed = (size_t) -1; /* definite failure */ 428 break; 429 } 430 } 431 } 432 433 try { 434 if ((kwargs_consumed == nkwargs || it->has_kwargs) && 435 (nargs_ == it->nargs || it->has_args)) 436 result = it->impl(it, args_, kwargs, parent); 437 } catch (reference_cast_error &) { 438 result = PYBIND11_TRY_NEXT_OVERLOAD; 439 } 440 441 if (result.ptr() != PYBIND11_TRY_NEXT_OVERLOAD) 442 break; 443 } 444 } catch (error_already_set &e) { 445 e.restore(); 446 return nullptr; 447 } catch (...) { 448 /* When an exception is caught, give each registered exception 449 translator a chance to translate it to a Python exception 450 in reverse order of registration. 451 452 A translator may choose to do one of the following: 453 454 - catch the exception and call PyErr_SetString or PyErr_SetObject 455 to set a standard (or custom) Python exception, or 456 - do nothing and let the exception fall through to the next translator, or 457 - delegate translation to the next translator by throwing a new type of exception. */ 458 459 auto last_exception = std::current_exception(); 460 auto ®istered_exception_translators = pybind11::detail::get_internals().registered_exception_translators; 461 for (auto& translator : registered_exception_translators) { 462 try { 463 translator(last_exception); 464 } catch (...) { 465 last_exception = std::current_exception(); 466 continue; 467 } 468 return nullptr; 469 } 470 PyErr_SetString(PyExc_SystemError, "Exception escaped from default exception translator!"); 471 return nullptr; 472 } 473 474 if (result.ptr() == PYBIND11_TRY_NEXT_OVERLOAD) { 475 if (overloads->is_operator) 476 return handle(Py_NotImplemented).inc_ref().ptr(); 477 478 std::string msg = std::string(overloads->name) + "(): incompatible " + 479 std::string(overloads->is_constructor ? "constructor" : "function") + 480 " arguments. The following argument types are supported:\n"; 481 482 int ctr = 0; 483 for (detail::function_record *it2 = overloads; it2 != nullptr; it2 = it2->next) { 484 msg += " "+ std::to_string(++ctr) + ". "; 485 486 bool wrote_sig = false; 487 if (overloads->is_constructor) { 488 // For a constructor, rewrite `(self: Object, arg0, ...) -> NoneType` as `Object(arg0, ...)` 489 std::string sig = it2->signature; 490 size_t start = sig.find('(') + 7; // skip "(self: " 491 if (start < sig.size()) { 492 // End at the , for the next argument 493 size_t end = sig.find(", "), next = end + 2; 494 size_t ret = sig.rfind(" -> "); 495 // Or the ), if there is no comma: 496 if (end >= sig.size()) next = end = sig.find(')'); 497 if (start < end && next < sig.size()) { 498 msg.append(sig, start, end - start); 499 msg += '('; 500 msg.append(sig, next, ret - next); 501 wrote_sig = true; 502 } 503 } 504 } 505 if (!wrote_sig) msg += it2->signature; 506 507 msg += "\n"; 508 } 509 msg += "\nInvoked with: "; 510 auto args_ = reinterpret_borrow<tuple>(args); 511 for (size_t ti = overloads->is_constructor ? 1 : 0; ti < args_.size(); ++ti) { 512 msg += pybind11::repr(args_[ti]); 513 if ((ti + 1) != args_.size() ) 514 msg += ", "; 515 } 516 PyErr_SetString(PyExc_TypeError, msg.c_str()); 517 return nullptr; 518 } else if (!result) { 519 std::string msg = "Unable to convert function return value to a " 520 "Python type! The signature was\n\t"; 521 msg += it->signature; 522 PyErr_SetString(PyExc_TypeError, msg.c_str()); 523 return nullptr; 524 } else { 525 if (overloads->is_constructor) { 526 /* When a constructor ran successfully, the corresponding 527 holder type (e.g. std::unique_ptr) must still be initialized. */ 528 PyObject *inst = PyTuple_GET_ITEM(args, 0); 529 auto tinfo = detail::get_type_info(Py_TYPE(inst)); 530 tinfo->init_holder(inst, nullptr); 531 } 532 return result.ptr(); 533 } 534 } 535}; 536 537/// Wrapper for Python extension modules 538class module : public object { 539public: 540 PYBIND11_OBJECT_DEFAULT(module, object, PyModule_Check) 541 542 explicit module(const char *name, const char *doc = nullptr) { 543 if (!options::show_user_defined_docstrings()) doc = nullptr; 544#if PY_MAJOR_VERSION >= 3 545 PyModuleDef *def = new PyModuleDef(); 546 memset(def, 0, sizeof(PyModuleDef)); 547 def->m_name = name; 548 def->m_doc = doc; 549 def->m_size = -1; 550 Py_INCREF(def); 551 m_ptr = PyModule_Create(def); 552#else 553 m_ptr = Py_InitModule3(name, nullptr, doc); 554#endif 555 if (m_ptr == nullptr) 556 pybind11_fail("Internal error in module::module()"); 557 inc_ref(); 558 } 559 560 template <typename Func, typename... Extra> 561 module &def(const char *name_, Func &&f, const Extra& ... extra) { 562 cpp_function func(std::forward<Func>(f), name(name_), scope(*this), 563 sibling(getattr(*this, name_, none())), extra...); 564 // NB: allow overwriting here because cpp_function sets up a chain with the intention of 565 // overwriting (and has already checked internally that it isn't overwriting non-functions). 566 add_object(name_, func, true /* overwrite */); 567 return *this; 568 } 569 570 module def_submodule(const char *name, const char *doc = nullptr) { 571 std::string full_name = std::string(PyModule_GetName(m_ptr)) 572 + std::string(".") + std::string(name); 573 auto result = reinterpret_borrow<module>(PyImport_AddModule(full_name.c_str())); 574 if (doc && options::show_user_defined_docstrings()) 575 result.attr("__doc__") = pybind11::str(doc); 576 attr(name) = result; 577 return result; 578 } 579 580 static module import(const char *name) { 581 PyObject *obj = PyImport_ImportModule(name); 582 if (!obj) 583 throw error_already_set(); 584 return reinterpret_steal<module>(obj); 585 } 586 587 // Adds an object to the module using the given name. Throws if an object with the given name 588 // already exists. 589 // 590 // overwrite should almost always be false: attempting to overwrite objects that pybind11 has 591 // established will, in most cases, break things. 592 PYBIND11_NOINLINE void add_object(const char *name, object &obj, bool overwrite = false) { 593 if (!overwrite && hasattr(*this, name)) 594 pybind11_fail("Error during initialization: multiple incompatible definitions with name \"" + 595 std::string(name) + "\""); 596 597 obj.inc_ref(); // PyModule_AddObject() steals a reference 598 PyModule_AddObject(ptr(), name, obj.ptr()); 599 } 600}; 601 602NAMESPACE_BEGIN(detail) 603extern "C" inline PyObject *get_dict(PyObject *op, void *) { 604 PyObject *&dict = *_PyObject_GetDictPtr(op); 605 if (!dict) { 606 dict = PyDict_New(); 607 } 608 Py_XINCREF(dict); 609 return dict; 610} 611 612extern "C" inline int set_dict(PyObject *op, PyObject *new_dict, void *) { 613 if (!PyDict_Check(new_dict)) { 614 PyErr_Format(PyExc_TypeError, "__dict__ must be set to a dictionary, not a '%.200s'", 615 Py_TYPE(new_dict)->tp_name); 616 return -1; 617 } 618 PyObject *&dict = *_PyObject_GetDictPtr(op); 619 Py_INCREF(new_dict); 620 Py_CLEAR(dict); 621 dict = new_dict; 622 return 0; 623} 624 625static PyGetSetDef generic_getset[] = { 626 {const_cast<char*>("__dict__"), get_dict, set_dict, nullptr, nullptr}, 627 {nullptr, nullptr, nullptr, nullptr, nullptr} 628}; 629 630/// Generic support for creating new Python heap types 631class generic_type : public object { 632 template <typename...> friend class class_; 633public: 634 PYBIND11_OBJECT_DEFAULT(generic_type, object, PyType_Check) 635protected: 636 void initialize(type_record *rec) { 637 auto &internals = get_internals(); 638 auto tindex = std::type_index(*(rec->type)); 639 640 if (get_type_info(*(rec->type))) 641 pybind11_fail("generic_type: type \"" + std::string(rec->name) + 642 "\" is already registered!"); 643 644 auto name = reinterpret_steal<object>(PYBIND11_FROM_STRING(rec->name)); 645 object scope_module; 646 if (rec->scope) { 647 if (hasattr(rec->scope, rec->name)) 648 pybind11_fail("generic_type: cannot initialize type \"" + std::string(rec->name) + 649 "\": an object with that name is already defined"); 650 651 if (hasattr(rec->scope, "__module__")) { 652 scope_module = rec->scope.attr("__module__"); 653 } else if (hasattr(rec->scope, "__name__")) { 654 scope_module = rec->scope.attr("__name__"); 655 } 656 } 657 658#if PY_MAJOR_VERSION >= 3 && PY_MINOR_VERSION >= 3 659 /* Qualified names for Python >= 3.3 */ 660 object scope_qualname; 661 if (rec->scope && hasattr(rec->scope, "__qualname__")) 662 scope_qualname = rec->scope.attr("__qualname__"); 663 object ht_qualname; 664 if (scope_qualname) { 665 ht_qualname = reinterpret_steal<object>(PyUnicode_FromFormat( 666 "%U.%U", scope_qualname.ptr(), name.ptr())); 667 } else { 668 ht_qualname = name; 669 } 670#endif 671 672 size_t num_bases = rec->bases.size(); 673 auto bases = tuple(rec->bases); 674 675 std::string full_name = (scope_module ? ((std::string) pybind11::str(scope_module) + "." + rec->name) 676 : std::string(rec->name)); 677 678 char *tp_doc = nullptr; 679 if (rec->doc && options::show_user_defined_docstrings()) { 680 /* Allocate memory for docstring (using PyObject_MALLOC, since 681 Python will free this later on) */ 682 size_t size = strlen(rec->doc) + 1; 683 tp_doc = (char *) PyObject_MALLOC(size); 684 memcpy((void *) tp_doc, rec->doc, size); 685 } 686 687 /* Danger zone: from now (and until PyType_Ready), make sure to 688 issue no Python C API calls which could potentially invoke the 689 garbage collector (the GC will call type_traverse(), which will in 690 turn find the newly constructed type in an invalid state) */ 691 692 auto type_holder = reinterpret_steal<object>(PyType_Type.tp_alloc(&PyType_Type, 0)); 693 auto type = (PyHeapTypeObject*) type_holder.ptr(); 694 695 if (!type_holder || !name) 696 pybind11_fail(std::string(rec->name) + ": Unable to create type object!"); 697 698 /* Register supplemental type information in C++ dict */ 699 detail::type_info *tinfo = new detail::type_info(); 700 tinfo->type = (PyTypeObject *) type; 701 tinfo->type_size = rec->type_size; 702 tinfo->init_holder = rec->init_holder; 703 tinfo->direct_conversions = &internals.direct_conversions[tindex]; 704 internals.registered_types_cpp[tindex] = tinfo; 705 internals.registered_types_py[type] = tinfo; 706 707 /* Basic type attributes */ 708 type->ht_type.tp_name = strdup(full_name.c_str()); 709 type->ht_type.tp_basicsize = (ssize_t) rec->instance_size; 710 711 if (num_bases > 0) { 712 type->ht_type.tp_base = (PyTypeObject *) ((object) bases[0]).inc_ref().ptr(); 713 type->ht_type.tp_bases = bases.release().ptr(); 714 rec->multiple_inheritance |= num_bases > 1; 715 } 716 717 type->ht_name = name.release().ptr(); 718 719#if PY_MAJOR_VERSION >= 3 && PY_MINOR_VERSION >= 3 720 type->ht_qualname = ht_qualname.release().ptr(); 721#endif 722 723 /* Supported protocols */ 724 type->ht_type.tp_as_number = &type->as_number; 725 type->ht_type.tp_as_sequence = &type->as_sequence; 726 type->ht_type.tp_as_mapping = &type->as_mapping; 727 728 /* Supported elementary operations */ 729 type->ht_type.tp_init = (initproc) init; 730 type->ht_type.tp_new = (newfunc) new_instance; 731 type->ht_type.tp_dealloc = rec->dealloc; 732 733 /* Support weak references (needed for the keep_alive feature) */ 734 type->ht_type.tp_weaklistoffset = offsetof(instance_essentials<void>, weakrefs); 735 736 /* Flags */ 737 type->ht_type.tp_flags |= Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HEAPTYPE; 738#if PY_MAJOR_VERSION < 3 739 type->ht_type.tp_flags |= Py_TPFLAGS_CHECKTYPES; 740#endif 741 type->ht_type.tp_flags &= ~Py_TPFLAGS_HAVE_GC; 742 743 /* Support dynamic attributes */ 744 if (rec->dynamic_attr) { 745 type->ht_type.tp_flags |= Py_TPFLAGS_HAVE_GC; 746 type->ht_type.tp_dictoffset = type->ht_type.tp_basicsize; // place the dict at the end 747 type->ht_type.tp_basicsize += sizeof(PyObject *); // and allocate enough space for it 748 type->ht_type.tp_getset = generic_getset; 749 type->ht_type.tp_traverse = traverse; 750 type->ht_type.tp_clear = clear; 751 } 752 753 type->ht_type.tp_doc = tp_doc; 754 755 if (PyType_Ready(&type->ht_type) < 0) 756 pybind11_fail(std::string(rec->name) + ": PyType_Ready failed (" + 757 detail::error_string() + ")!"); 758 759 m_ptr = type_holder.ptr(); 760 761 if (scope_module) // Needed by pydoc 762 attr("__module__") = scope_module; 763 764 /* Register type with the parent scope */ 765 if (rec->scope) 766 rec->scope.attr(handle(type->ht_name)) = *this; 767 768 if (rec->multiple_inheritance) 769 mark_parents_nonsimple(&type->ht_type); 770 771 type_holder.release(); 772 } 773 774 /// Helper function which tags all parents of a type using mult. inheritance 775 void mark_parents_nonsimple(PyTypeObject *value) { 776 auto t = reinterpret_borrow<tuple>(value->tp_bases); 777 for (handle h : t) { 778 auto tinfo2 = get_type_info((PyTypeObject *) h.ptr()); 779 if (tinfo2) 780 tinfo2->simple_type = false; 781 mark_parents_nonsimple((PyTypeObject *) h.ptr()); 782 } 783 } 784 785 /// Allocate a metaclass on demand (for static properties) 786 handle metaclass() { 787 auto &ht_type = ((PyHeapTypeObject *) m_ptr)->ht_type; 788 auto &ob_type = PYBIND11_OB_TYPE(ht_type); 789 790 if (ob_type == &PyType_Type) { 791 std::string name_ = std::string(ht_type.tp_name) + "__Meta"; 792#if PY_MAJOR_VERSION >= 3 && PY_MINOR_VERSION >= 3 793 auto ht_qualname = reinterpret_steal<object>(PyUnicode_FromFormat("%U__Meta", attr("__qualname__").ptr())); 794#endif 795 auto name = reinterpret_steal<object>(PYBIND11_FROM_STRING(name_.c_str())); 796 auto type_holder = reinterpret_steal<object>(PyType_Type.tp_alloc(&PyType_Type, 0)); 797 if (!type_holder || !name) 798 pybind11_fail("generic_type::metaclass(): unable to create type object!"); 799 800 auto type = (PyHeapTypeObject*) type_holder.ptr(); 801 type->ht_name = name.release().ptr(); 802 803#if PY_MAJOR_VERSION >= 3 && PY_MINOR_VERSION >= 3 804 /* Qualified names for Python >= 3.3 */ 805 type->ht_qualname = ht_qualname.release().ptr(); 806#endif 807 type->ht_type.tp_name = strdup(name_.c_str()); 808 type->ht_type.tp_base = ob_type; 809 type->ht_type.tp_flags |= (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE) & 810 ~Py_TPFLAGS_HAVE_GC; 811 812 if (PyType_Ready(&type->ht_type) < 0) 813 pybind11_fail("generic_type::metaclass(): PyType_Ready failed!"); 814 815 ob_type = (PyTypeObject *) type_holder.release().ptr(); 816 } 817 return handle((PyObject *) ob_type); 818 } 819 820 static int init(void *self, PyObject *, PyObject *) { 821 std::string msg = std::string(Py_TYPE(self)->tp_name) + ": No constructor defined!"; 822 PyErr_SetString(PyExc_TypeError, msg.c_str()); 823 return -1; 824 } 825 826 static PyObject *new_instance(PyTypeObject *type, PyObject *, PyObject *) { 827 instance<void> *self = (instance<void> *) PyType_GenericAlloc((PyTypeObject *) type, 0); 828 auto tinfo = detail::get_type_info(type); 829 self->value = ::operator new(tinfo->type_size); 830 self->owned = true; 831 self->holder_constructed = false; 832 detail::get_internals().registered_instances.emplace(self->value, (PyObject *) self); 833 return (PyObject *) self; 834 } 835 836 static void dealloc(instance<void> *self) { 837 if (self->value) { 838 auto instance_type = Py_TYPE(self); 839 auto ®istered_instances = detail::get_internals().registered_instances; 840 auto range = registered_instances.equal_range(self->value); 841 bool found = false; 842 for (auto it = range.first; it != range.second; ++it) { 843 if (instance_type == Py_TYPE(it->second)) { 844 registered_instances.erase(it); 845 found = true; 846 break; 847 } 848 } 849 if (!found) 850 pybind11_fail("generic_type::dealloc(): Tried to deallocate unregistered instance!"); 851 852 if (self->weakrefs) 853 PyObject_ClearWeakRefs((PyObject *) self); 854 855 PyObject **dict_ptr = _PyObject_GetDictPtr((PyObject *) self); 856 if (dict_ptr) { 857 Py_CLEAR(*dict_ptr); 858 } 859 } 860 Py_TYPE(self)->tp_free((PyObject*) self); 861 } 862 863 static int traverse(PyObject *op, visitproc visit, void *arg) { 864 PyObject *&dict = *_PyObject_GetDictPtr(op); 865 Py_VISIT(dict); 866 return 0; 867 } 868 869 static int clear(PyObject *op) { 870 PyObject *&dict = *_PyObject_GetDictPtr(op); 871 Py_CLEAR(dict); 872 return 0; 873 } 874 875 void install_buffer_funcs( 876 buffer_info *(*get_buffer)(PyObject *, void *), 877 void *get_buffer_data) { 878 PyHeapTypeObject *type = (PyHeapTypeObject*) m_ptr; 879 type->ht_type.tp_as_buffer = &type->as_buffer; 880#if PY_MAJOR_VERSION < 3 881 type->ht_type.tp_flags |= Py_TPFLAGS_HAVE_NEWBUFFER; 882#endif 883 type->as_buffer.bf_getbuffer = getbuffer; 884 type->as_buffer.bf_releasebuffer = releasebuffer; 885 auto tinfo = detail::get_type_info(&type->ht_type); 886 tinfo->get_buffer = get_buffer; 887 tinfo->get_buffer_data = get_buffer_data; 888 } 889 890 static int getbuffer(PyObject *obj, Py_buffer *view, int flags) { 891 auto tinfo = detail::get_type_info(Py_TYPE(obj)); 892 if (view == nullptr || obj == nullptr || !tinfo || !tinfo->get_buffer) { 893 PyErr_SetString(PyExc_BufferError, "generic_type::getbuffer(): Internal error"); 894 return -1; 895 } 896 memset(view, 0, sizeof(Py_buffer)); 897 buffer_info *info = tinfo->get_buffer(obj, tinfo->get_buffer_data); 898 view->obj = obj; 899 view->ndim = 1; 900 view->internal = info; 901 view->buf = info->ptr; 902 view->itemsize = (ssize_t) info->itemsize; 903 view->len = view->itemsize; 904 for (auto s : info->shape) 905 view->len *= s; 906 if ((flags & PyBUF_FORMAT) == PyBUF_FORMAT) 907 view->format = const_cast<char *>(info->format.c_str()); 908 if ((flags & PyBUF_STRIDES) == PyBUF_STRIDES) { 909 view->ndim = (int) info->ndim; 910 view->strides = (ssize_t *) &info->strides[0]; 911 view->shape = (ssize_t *) &info->shape[0]; 912 } 913 Py_INCREF(view->obj); 914 return 0; 915 } 916 917 static void releasebuffer(PyObject *, Py_buffer *view) { delete (buffer_info *) view->internal; } 918}; 919 920NAMESPACE_END(detail) 921 922template <typename type_, typename... options> 923class class_ : public detail::generic_type { 924 template <typename T> using is_holder = detail::is_holder_type<type_, T>; 925 template <typename T> using is_subtype = detail::bool_constant<std::is_base_of<type_, T>::value && !std::is_same<T, type_>::value>; 926 template <typename T> using is_base = detail::bool_constant<std::is_base_of<T, type_>::value && !std::is_same<T, type_>::value>; 927 template <typename T> using is_valid_class_option = 928 detail::bool_constant< 929 is_holder<T>::value || 930 is_subtype<T>::value || 931 is_base<T>::value 932 >; 933 934public: 935 using type = type_; 936 using type_alias = detail::first_of_t<is_subtype, void, options...>; 937 constexpr static bool has_alias = !std::is_void<type_alias>::value; 938 using holder_type = detail::first_of_t<is_holder, std::unique_ptr<type>, options...>; 939 using instance_type = detail::instance<type, holder_type>; 940 941 static_assert(detail::all_of_t<is_valid_class_option, options...>::value, 942 "Unknown/invalid class_ template parameters provided"); 943 944 PYBIND11_OBJECT(class_, generic_type, PyType_Check) 945 946 template <typename... Extra> 947 class_(handle scope, const char *name, const Extra &... extra) { 948 detail::type_record record; 949 record.scope = scope; 950 record.name = name; 951 record.type = &typeid(type); 952 record.type_size = sizeof(detail::conditional_t<has_alias, type_alias, type>); 953 record.instance_size = sizeof(instance_type); 954 record.init_holder = init_holder; 955 record.dealloc = dealloc; 956 957 /* Register base classes specified via template arguments to class_, if any */ 958 bool unused[] = { (add_base<options>(record), false)..., false }; 959 (void) unused; 960 961 /* Process optional arguments, if any */ 962 detail::process_attributes<Extra...>::init(extra..., &record); 963 964 detail::generic_type::initialize(&record); 965 966 if (has_alias) { 967 auto &instances = pybind11::detail::get_internals().registered_types_cpp; 968 instances[std::type_index(typeid(type_alias))] = instances[std::type_index(typeid(type))]; 969 } 970 } 971 972 template <typename Base, detail::enable_if_t<is_base<Base>::value, int> = 0> 973 static void add_base(detail::type_record &rec) { 974 rec.add_base(&typeid(Base), [](void *src) -> void * { 975 return static_cast<Base *>(reinterpret_cast<type *>(src)); 976 }); 977 } 978 979 template <typename Base, detail::enable_if_t<!is_base<Base>::value, int> = 0> 980 static void add_base(detail::type_record &) { } 981 982 template <typename Func, typename... Extra> 983 class_ &def(const char *name_, Func&& f, const Extra&... extra) { 984 cpp_function cf(std::forward<Func>(f), name(name_), is_method(*this), 985 sibling(getattr(*this, name_, none())), extra...); 986 attr(cf.name()) = cf; 987 return *this; 988 } 989 990 template <typename Func, typename... Extra> class_ & 991 def_static(const char *name_, Func f, const Extra&... extra) { 992 cpp_function cf(std::forward<Func>(f), name(name_), scope(*this), 993 sibling(getattr(*this, name_, none())), extra...); 994 attr(cf.name()) = cf; 995 return *this; 996 } 997 998 template <detail::op_id id, detail::op_type ot, typename L, typename R, typename... Extra> 999 class_ &def(const detail::op_<id, ot, L, R> &op, const Extra&... extra) { 1000 op.execute(*this, extra...); 1001 return *this; 1002 } 1003 1004 template <detail::op_id id, detail::op_type ot, typename L, typename R, typename... Extra> 1005 class_ & def_cast(const detail::op_<id, ot, L, R> &op, const Extra&... extra) { 1006 op.execute_cast(*this, extra...); 1007 return *this; 1008 } 1009 1010 template <typename... Args, typename... Extra> 1011 class_ &def(const detail::init<Args...> &init, const Extra&... extra) { 1012 init.execute(*this, extra...); 1013 return *this; 1014 } 1015 1016 template <typename... Args, typename... Extra> 1017 class_ &def(const detail::init_alias<Args...> &init, const Extra&... extra) { 1018 init.execute(*this, extra...); 1019 return *this; 1020 } 1021 1022 template <typename Func> class_& def_buffer(Func &&func) { 1023 struct capture { Func func; }; 1024 capture *ptr = new capture { std::forward<Func>(func) }; 1025 install_buffer_funcs([](PyObject *obj, void *ptr) -> buffer_info* { 1026 detail::type_caster<type> caster; 1027 if (!caster.load(obj, false)) 1028 return nullptr; 1029 return new buffer_info(((capture *) ptr)->func(caster)); 1030 }, ptr); 1031 return *this; 1032 } 1033 1034 template <typename C, typename D, typename... Extra> 1035 class_ &def_readwrite(const char *name, D C::*pm, const Extra&... extra) { 1036 cpp_function fget([pm](const C &c) -> const D &{ return c.*pm; }, is_method(*this)), 1037 fset([pm](C &c, const D &value) { c.*pm = value; }, is_method(*this)); 1038 def_property(name, fget, fset, return_value_policy::reference_internal, extra...); 1039 return *this; 1040 } 1041 1042 template <typename C, typename D, typename... Extra> 1043 class_ &def_readonly(const char *name, const D C::*pm, const Extra& ...extra) { 1044 cpp_function fget([pm](const C &c) -> const D &{ return c.*pm; }, is_method(*this)); 1045 def_property_readonly(name, fget, return_value_policy::reference_internal, extra...); 1046 return *this; 1047 } 1048 1049 template <typename D, typename... Extra> 1050 class_ &def_readwrite_static(const char *name, D *pm, const Extra& ...extra) { 1051 cpp_function fget([pm](object) -> const D &{ return *pm; }, scope(*this)), 1052 fset([pm](object, const D &value) { *pm = value; }, scope(*this)); 1053 def_property_static(name, fget, fset, return_value_policy::reference, extra...); 1054 return *this; 1055 } 1056 1057 template <typename D, typename... Extra> 1058 class_ &def_readonly_static(const char *name, const D *pm, const Extra& ...extra) { 1059 cpp_function fget([pm](object) -> const D &{ return *pm; }, scope(*this)); 1060 def_property_readonly_static(name, fget, return_value_policy::reference, extra...); 1061 return *this; 1062 } 1063 1064 /// Uses return_value_policy::reference_internal by default 1065 template <typename Getter, typename... Extra> 1066 class_ &def_property_readonly(const char *name, const Getter &fget, const Extra& ...extra) { 1067 return def_property_readonly(name, cpp_function(fget), return_value_policy::reference_internal, extra...); 1068 } 1069 1070 /// Uses cpp_function's return_value_policy by default 1071 template <typename... Extra> 1072 class_ &def_property_readonly(const char *name, const cpp_function &fget, const Extra& ...extra) { 1073 return def_property(name, fget, cpp_function(), extra...); 1074 } 1075 1076 /// Uses return_value_policy::reference by default 1077 template <typename Getter, typename... Extra> 1078 class_ &def_property_readonly_static(const char *name, const Getter &fget, const Extra& ...extra) { 1079 return def_property_readonly_static(name, cpp_function(fget), return_value_policy::reference, extra...); 1080 } 1081 1082 /// Uses cpp_function's return_value_policy by default 1083 template <typename... Extra> 1084 class_ &def_property_readonly_static(const char *name, const cpp_function &fget, const Extra& ...extra) { 1085 return def_property_static(name, fget, cpp_function(), extra...); 1086 } 1087 1088 /// Uses return_value_policy::reference_internal by default 1089 template <typename Getter, typename... Extra> 1090 class_ &def_property(const char *name, const Getter &fget, const cpp_function &fset, const Extra& ...extra) { 1091 return def_property(name, cpp_function(fget), fset, return_value_policy::reference_internal, extra...); 1092 } 1093 1094 /// Uses cpp_function's return_value_policy by default 1095 template <typename... Extra> 1096 class_ &def_property(const char *name, const cpp_function &fget, const cpp_function &fset, const Extra& ...extra) { 1097 return def_property_static(name, fget, fset, is_method(*this), extra...); 1098 } 1099 1100 /// Uses return_value_policy::reference by default 1101 template <typename Getter, typename... Extra> 1102 class_ &def_property_static(const char *name, const Getter &fget, const cpp_function &fset, const Extra& ...extra) { 1103 return def_property_static(name, cpp_function(fget), fset, return_value_policy::reference, extra...); 1104 } 1105 1106 /// Uses cpp_function's return_value_policy by default 1107 template <typename... Extra> 1108 class_ &def_property_static(const char *name, const cpp_function &fget, const cpp_function &fset, const Extra& ...extra) { 1109 auto rec_fget = get_function_record(fget), rec_fset = get_function_record(fset); 1110 char *doc_prev = rec_fget->doc; /* 'extra' field may include a property-specific documentation string */ 1111 detail::process_attributes<Extra...>::init(extra..., rec_fget); 1112 if (rec_fget->doc && rec_fget->doc != doc_prev) { 1113 free(doc_prev); 1114 rec_fget->doc = strdup(rec_fget->doc); 1115 } 1116 if (rec_fset) { 1117 doc_prev = rec_fset->doc; 1118 detail::process_attributes<Extra...>::init(extra..., rec_fset); 1119 if (rec_fset->doc && rec_fset->doc != doc_prev) { 1120 free(doc_prev); 1121 rec_fset->doc = strdup(rec_fset->doc); 1122 } 1123 } 1124 pybind11::str doc_obj = pybind11::str((rec_fget->doc && pybind11::options::show_user_defined_docstrings()) ? rec_fget->doc : ""); 1125 const auto property = reinterpret_steal<object>( 1126 PyObject_CallFunctionObjArgs((PyObject *) &PyProperty_Type, fget.ptr() ? fget.ptr() : Py_None, 1127 fset.ptr() ? fset.ptr() : Py_None, Py_None, doc_obj.ptr(), nullptr)); 1128 if (rec_fget->is_method && rec_fget->scope) 1129 attr(name) = property; 1130 else 1131 metaclass().attr(name) = property; 1132 return *this; 1133 } 1134 1135private: 1136 /// Initialize holder object, variant 1: object derives from enable_shared_from_this 1137 template <typename T> 1138 static void init_holder_helper(instance_type *inst, const holder_type * /* unused */, const std::enable_shared_from_this<T> * /* dummy */) { 1139 try { 1140 new (&inst->holder) holder_type(std::static_pointer_cast<typename holder_type::element_type>(inst->value->shared_from_this())); 1141 inst->holder_constructed = true; 1142 } catch (const std::bad_weak_ptr &) { 1143 if (inst->owned) { 1144 new (&inst->holder) holder_type(inst->value); 1145 inst->holder_constructed = true; 1146 } 1147 } 1148 } 1149 1150 /// Initialize holder object, variant 2: try to construct from existing holder object, if possible 1151 template <typename T = holder_type, 1152 detail::enable_if_t<std::is_copy_constructible<T>::value, int> = 0> 1153 static void init_holder_helper(instance_type *inst, const holder_type *holder_ptr, const void * /* dummy */) { 1154 if (holder_ptr) { 1155 new (&inst->holder) holder_type(*holder_ptr); 1156 inst->holder_constructed = true; 1157 } else if (inst->owned) { 1158 new (&inst->holder) holder_type(inst->value); 1159 inst->holder_constructed = true; 1160 } 1161 } 1162 1163 /// Initialize holder object, variant 3: holder is not copy constructible (e.g. unique_ptr), always initialize from raw pointer 1164 template <typename T = holder_type, 1165 detail::enable_if_t<!std::is_copy_constructible<T>::value, int> = 0> 1166 static void init_holder_helper(instance_type *inst, const holder_type * /* unused */, const void * /* dummy */) { 1167 if (inst->owned) { 1168 new (&inst->holder) holder_type(inst->value); 1169 inst->holder_constructed = true; 1170 } 1171 } 1172 1173 /// Initialize holder object of an instance, possibly given a pointer to an existing holder 1174 static void init_holder(PyObject *inst_, const void *holder_ptr) { 1175 auto inst = (instance_type *) inst_; 1176 init_holder_helper(inst, (const holder_type *) holder_ptr, inst->value); 1177 } 1178 1179 static void dealloc(PyObject *inst_) { 1180 instance_type *inst = (instance_type *) inst_; 1181 if (inst->holder_constructed) 1182 inst->holder.~holder_type(); 1183 else if (inst->owned) 1184 ::operator delete(inst->value); 1185 1186 generic_type::dealloc((detail::instance<void> *) inst); 1187 } 1188 1189 static detail::function_record *get_function_record(handle h) { 1190 h = detail::get_function(h); 1191 return h ? (detail::function_record *) reinterpret_borrow<capsule>(PyCFunction_GetSelf(h.ptr())) 1192 : nullptr; 1193 } 1194}; 1195 1196/// Binds C++ enumerations and enumeration classes to Python 1197template <typename Type> class enum_ : public class_<Type> { 1198public: 1199 using class_<Type>::def; 1200 using Scalar = typename std::underlying_type<Type>::type; 1201 template <typename T> using arithmetic_tag = std::is_same<T, arithmetic>; 1202 1203 template <typename... Extra> 1204 enum_(const handle &scope, const char *name, const Extra&... extra) 1205 : class_<Type>(scope, name, extra...), m_parent(scope) { 1206 1207 constexpr bool is_arithmetic = 1208 !std::is_same<detail::first_of_t<arithmetic_tag, void, Extra...>, 1209 void>::value; 1210 1211 auto entries = new std::unordered_map<Scalar, const char *>(); 1212 def("__repr__", [name, entries](Type value) -> std::string { 1213 auto it = entries->find((Scalar) value); 1214 return std::string(name) + "." + 1215 ((it == entries->end()) ? std::string("???") 1216 : std::string(it->second)); 1217 }); 1218 def("__init__", [](Type& value, Scalar i) { value = (Type)i; }); 1219 def("__init__", [](Type& value, Scalar i) { new (&value) Type((Type) i); }); 1220 def("__int__", [](Type value) { return (Scalar) value; }); 1221 def("__eq__", [](const Type &value, Type *value2) { return value2 && value == *value2; }); 1222 def("__ne__", [](const Type &value, Type *value2) { return !value2 || value != *value2; }); 1223 if (is_arithmetic) { 1224 def("__lt__", [](const Type &value, Type *value2) { return value2 && value < *value2; }); 1225 def("__gt__", [](const Type &value, Type *value2) { return value2 && value > *value2; }); 1226 def("__le__", [](const Type &value, Type *value2) { return value2 && value <= *value2; }); 1227 def("__ge__", [](const Type &value, Type *value2) { return value2 && value >= *value2; }); 1228 } 1229 if (std::is_convertible<Type, Scalar>::value) { 1230 // Don't provide comparison with the underlying type if the enum isn't convertible, 1231 // i.e. if Type is a scoped enum, mirroring the C++ behaviour. (NB: we explicitly 1232 // convert Type to Scalar below anyway because this needs to compile). 1233 def("__eq__", [](const Type &value, Scalar value2) { return (Scalar) value == value2; }); 1234 def("__ne__", [](const Type &value, Scalar value2) { return (Scalar) value != value2; }); 1235 if (is_arithmetic) { 1236 def("__lt__", [](const Type &value, Scalar value2) { return (Scalar) value < value2; }); 1237 def("__gt__", [](const Type &value, Scalar value2) { return (Scalar) value > value2; }); 1238 def("__le__", [](const Type &value, Scalar value2) { return (Scalar) value <= value2; }); 1239 def("__ge__", [](const Type &value, Scalar value2) { return (Scalar) value >= value2; }); 1240 def("__invert__", [](const Type &value) { return ~((Scalar) value); }); 1241 def("__and__", [](const Type &value, Scalar value2) { return (Scalar) value & value2; }); 1242 def("__or__", [](const Type &value, Scalar value2) { return (Scalar) value | value2; }); 1243 def("__xor__", [](const Type &value, Scalar value2) { return (Scalar) value ^ value2; }); 1244 def("__rand__", [](const Type &value, Scalar value2) { return (Scalar) value & value2; }); 1245 def("__ror__", [](const Type &value, Scalar value2) { return (Scalar) value | value2; }); 1246 def("__rxor__", [](const Type &value, Scalar value2) { return (Scalar) value ^ value2; }); 1247 def("__and__", [](const Type &value, const Type &value2) { return (Scalar) value & (Scalar) value2; }); 1248 def("__or__", [](const Type &value, const Type &value2) { return (Scalar) value | (Scalar) value2; }); 1249 def("__xor__", [](const Type &value, const Type &value2) { return (Scalar) value ^ (Scalar) value2; }); 1250 } 1251 } 1252 def("__hash__", [](const Type &value) { return (Scalar) value; }); 1253 // Pickling and unpickling -- needed for use with the 'multiprocessing' module 1254 def("__getstate__", [](const Type &value) { return pybind11::make_tuple((Scalar) value); }); 1255 def("__setstate__", [](Type &p, tuple t) { new (&p) Type((Type) t[0].cast<Scalar>()); }); 1256 m_entries = entries; 1257 } 1258 1259 /// Export enumeration entries into the parent scope 1260 enum_ &export_values() { 1261 PyObject *dict = ((PyTypeObject *) this->m_ptr)->tp_dict; 1262 PyObject *key, *value; 1263 ssize_t pos = 0; 1264 while (PyDict_Next(dict, &pos, &key, &value)) 1265 if (PyObject_IsInstance(value, this->m_ptr)) 1266 m_parent.attr(key) = value; 1267 return *this; 1268 } 1269 1270 /// Add an enumeration entry 1271 enum_& value(char const* name, Type value) { 1272 this->attr(name) = pybind11::cast(value, return_value_policy::copy); 1273 (*m_entries)[(Scalar) value] = name; 1274 return *this; 1275 } 1276private: 1277 std::unordered_map<Scalar, const char *> *m_entries; 1278 handle m_parent; 1279}; 1280 1281NAMESPACE_BEGIN(detail) 1282template <typename... Args> struct init { 1283 template <typename Class, typename... Extra, enable_if_t<!Class::has_alias, int> = 0> 1284 static void execute(Class &cl, const Extra&... extra) { 1285 using Base = typename Class::type; 1286 /// Function which calls a specific C++ in-place constructor 1287 cl.def("__init__", [](Base *self_, Args... args) { new (self_) Base(args...); }, extra...); 1288 } 1289 1290 template <typename Class, typename... Extra, 1291 enable_if_t<Class::has_alias && 1292 std::is_constructible<typename Class::type, Args...>::value, int> = 0> 1293 static void execute(Class &cl, const Extra&... extra) { 1294 using Base = typename Class::type; 1295 using Alias = typename Class::type_alias; 1296 handle cl_type = cl; 1297 cl.def("__init__", [cl_type](handle self_, Args... args) { 1298 if (self_.get_type() == cl_type) 1299 new (self_.cast<Base *>()) Base(args...); 1300 else 1301 new (self_.cast<Alias *>()) Alias(args...); 1302 }, extra...); 1303 } 1304 1305 template <typename Class, typename... Extra, 1306 enable_if_t<Class::has_alias && 1307 !std::is_constructible<typename Class::type, Args...>::value, int> = 0> 1308 static void execute(Class &cl, const Extra&... extra) { 1309 init_alias<Args...>::execute(cl, extra...); 1310 } 1311}; 1312template <typename... Args> struct init_alias { 1313 template <typename Class, typename... Extra, 1314 enable_if_t<Class::has_alias && std::is_constructible<typename Class::type_alias, Args...>::value, int> = 0> 1315 static void execute(Class &cl, const Extra&... extra) { 1316 using Alias = typename Class::type_alias; 1317 cl.def("__init__", [](Alias *self_, Args... args) { new (self_) Alias(args...); }, extra...); 1318 } 1319}; 1320 1321 1322inline void keep_alive_impl(handle nurse, handle patient) { 1323 /* Clever approach based on weak references taken from Boost.Python */ 1324 if (!nurse || !patient) 1325 pybind11_fail("Could not activate keep_alive!"); 1326 1327 if (patient.is_none() || nurse.is_none()) 1328 return; /* Nothing to keep alive or nothing to be kept alive by */ 1329 1330 cpp_function disable_lifesupport( 1331 [patient](handle weakref) { patient.dec_ref(); weakref.dec_ref(); }); 1332 1333 weakref wr(nurse, disable_lifesupport); 1334 1335 patient.inc_ref(); /* reference patient and leak the weak reference */ 1336 (void) wr.release(); 1337} 1338 1339PYBIND11_NOINLINE inline void keep_alive_impl(int Nurse, int Patient, handle args, handle ret) { 1340 handle nurse (Nurse > 0 ? PyTuple_GetItem(args.ptr(), Nurse - 1) : ret.ptr()); 1341 handle patient(Patient > 0 ? PyTuple_GetItem(args.ptr(), Patient - 1) : ret.ptr()); 1342 1343 keep_alive_impl(nurse, patient); 1344} 1345 1346template <typename Iterator, typename Sentinel, bool KeyIterator, return_value_policy Policy> 1347struct iterator_state { 1348 Iterator it; 1349 Sentinel end; 1350 bool first; 1351}; 1352 1353NAMESPACE_END(detail) 1354 1355template <typename... Args> detail::init<Args...> init() { return detail::init<Args...>(); } 1356template <typename... Args> detail::init_alias<Args...> init_alias() { return detail::init_alias<Args...>(); } 1357 1358template <return_value_policy Policy = return_value_policy::reference_internal, 1359 typename Iterator, 1360 typename Sentinel, 1361 typename ValueType = decltype(*std::declval<Iterator>()), 1362 typename... Extra> 1363iterator make_iterator(Iterator first, Sentinel last, Extra &&... extra) { 1364 typedef detail::iterator_state<Iterator, Sentinel, false, Policy> state; 1365 1366 if (!detail::get_type_info(typeid(state), false)) { 1367 class_<state>(handle(), "iterator") 1368 .def("__iter__", [](state &s) -> state& { return s; }) 1369 .def("__next__", [](state &s) -> ValueType { 1370 if (!s.first) 1371 ++s.it; 1372 else 1373 s.first = false; 1374 if (s.it == s.end) 1375 throw stop_iteration(); 1376 return *s.it; 1377 }, std::forward<Extra>(extra)..., Policy); 1378 } 1379 1380 return (iterator) cast(state { first, last, true }); 1381} 1382 1383template <return_value_policy Policy = return_value_policy::reference_internal, 1384 typename Iterator, 1385 typename Sentinel, 1386 typename KeyType = decltype((*std::declval<Iterator>()).first), 1387 typename... Extra> 1388iterator make_key_iterator(Iterator first, Sentinel last, Extra &&... extra) { 1389 typedef detail::iterator_state<Iterator, Sentinel, true, Policy> state; 1390 1391 if (!detail::get_type_info(typeid(state), false)) { 1392 class_<state>(handle(), "iterator") 1393 .def("__iter__", [](state &s) -> state& { return s; }) 1394 .def("__next__", [](state &s) -> KeyType { 1395 if (!s.first) 1396 ++s.it; 1397 else 1398 s.first = false; 1399 if (s.it == s.end) 1400 throw stop_iteration(); 1401 return (*s.it).first; 1402 }, std::forward<Extra>(extra)..., Policy); 1403 } 1404 1405 return (iterator) cast(state { first, last, true }); 1406} 1407 1408template <return_value_policy Policy = return_value_policy::reference_internal, 1409 typename Type, typename... Extra> iterator make_iterator(Type &value, Extra&&... extra) { 1410 return make_iterator<Policy>(std::begin(value), std::end(value), extra...); 1411} 1412 1413template <return_value_policy Policy = return_value_policy::reference_internal, 1414 typename Type, typename... Extra> iterator make_key_iterator(Type &value, Extra&&... extra) { 1415 return make_key_iterator<Policy>(std::begin(value), std::end(value), extra...); 1416} 1417 1418template <typename InputType, typename OutputType> void implicitly_convertible() { 1419 auto implicit_caster = [](PyObject *obj, PyTypeObject *type) -> PyObject * { 1420 if (!detail::type_caster<InputType>().load(obj, false)) 1421 return nullptr; 1422 tuple args(1); 1423 args[0] = obj; 1424 PyObject *result = PyObject_Call((PyObject *) type, args.ptr(), nullptr); 1425 if (result == nullptr) 1426 PyErr_Clear(); 1427 return result; 1428 }; 1429 1430 if (auto tinfo = detail::get_type_info(typeid(OutputType))) 1431 tinfo->implicit_conversions.push_back(implicit_caster); 1432 else 1433 pybind11_fail("implicitly_convertible: Unable to find type " + type_id<OutputType>()); 1434} 1435 1436template <typename ExceptionTranslator> 1437void register_exception_translator(ExceptionTranslator&& translator) { 1438 detail::get_internals().registered_exception_translators.push_front( 1439 std::forward<ExceptionTranslator>(translator)); 1440} 1441 1442/* Wrapper to generate a new Python exception type. 1443 * 1444 * This should only be used with PyErr_SetString for now. 1445 * It is not (yet) possible to use as a py::base. 1446 * Template type argument is reserved for future use. 1447 */ 1448template <typename type> 1449class exception : public object { 1450public: 1451 exception(handle scope, const char *name, PyObject *base = PyExc_Exception) { 1452 std::string full_name = scope.attr("__name__").cast<std::string>() + 1453 std::string(".") + name; 1454 m_ptr = PyErr_NewException((char *) full_name.c_str(), base, NULL); 1455 if (hasattr(scope, name)) 1456 pybind11_fail("Error during initialization: multiple incompatible " 1457 "definitions with name \"" + std::string(name) + "\""); 1458 scope.attr(name) = *this; 1459 } 1460 1461 // Sets the current python exception to this exception object with the given message 1462 void operator()(const char *message) { 1463 PyErr_SetString(m_ptr, message); 1464 } 1465}; 1466 1467/** Registers a Python exception in `m` of the given `name` and installs an exception translator to 1468 * translate the C++ exception to the created Python exception using the exceptions what() method. 1469 * This is intended for simple exception translations; for more complex translation, register the 1470 * exception object and translator directly. 1471 */ 1472template <typename CppException> 1473exception<CppException> ®ister_exception(handle scope, 1474 const char *name, 1475 PyObject *base = PyExc_Exception) { 1476 static exception<CppException> ex(scope, name, base); 1477 register_exception_translator([](std::exception_ptr p) { 1478 if (!p) return; 1479 try { 1480 std::rethrow_exception(p); 1481 } catch (const CppException &e) { 1482 ex(e.what()); 1483 } 1484 }); 1485 return ex; 1486} 1487 1488NAMESPACE_BEGIN(detail) 1489PYBIND11_NOINLINE inline void print(tuple args, dict kwargs) { 1490 auto strings = tuple(args.size()); 1491 for (size_t i = 0; i < args.size(); ++i) { 1492 strings[i] = str(args[i]); 1493 } 1494 auto sep = kwargs.contains("sep") ? kwargs["sep"] : cast(" "); 1495 auto line = sep.attr("join")(strings); 1496 1497 object file; 1498 if (kwargs.contains("file")) { 1499 file = kwargs["file"].cast<object>(); 1500 } else { 1501 try { 1502 file = module::import("sys").attr("stdout"); 1503 } catch (const error_already_set &) { 1504 /* If print() is called from code that is executed as 1505 part of garbage collection during interpreter shutdown, 1506 importing 'sys' can fail. Give up rather than crashing the 1507 interpreter in this case. */ 1508 return; 1509 } 1510 } 1511 1512 auto write = file.attr("write"); 1513 write(line); 1514 write(kwargs.contains("end") ? kwargs["end"] : cast("\n")); 1515 1516 if (kwargs.contains("flush") && kwargs["flush"].cast<bool>()) 1517 file.attr("flush")(); 1518} 1519NAMESPACE_END(detail) 1520 1521template <return_value_policy policy = return_value_policy::automatic_reference, typename... Args> 1522void print(Args &&...args) { 1523 auto c = detail::collect_arguments<policy>(std::forward<Args>(args)...); 1524 detail::print(c.args(), c.kwargs()); 1525} 1526 1527#if defined(WITH_THREAD) 1528 1529/* The functions below essentially reproduce the PyGILState_* API using a RAII 1530 * pattern, but there are a few important differences: 1531 * 1532 * 1. When acquiring the GIL from an non-main thread during the finalization 1533 * phase, the GILState API blindly terminates the calling thread, which 1534 * is often not what is wanted. This API does not do this. 1535 * 1536 * 2. The gil_scoped_release function can optionally cut the relationship 1537 * of a PyThreadState and its associated thread, which allows moving it to 1538 * another thread (this is a fairly rare/advanced use case). 1539 * 1540 * 3. The reference count of an acquired thread state can be controlled. This 1541 * can be handy to prevent cases where callbacks issued from an external 1542 * thread would otherwise constantly construct and destroy thread state data 1543 * structures. 1544 * 1545 * See the Python bindings of NanoGUI (http://github.com/wjakob/nanogui) for an 1546 * example which uses features 2 and 3 to migrate the Python thread of 1547 * execution to another thread (to run the event loop on the original thread, 1548 * in this case). 1549 */ 1550 1551class gil_scoped_acquire { 1552public: 1553 PYBIND11_NOINLINE gil_scoped_acquire() { 1554 auto const &internals = detail::get_internals(); 1555 tstate = (PyThreadState *) PyThread_get_key_value(internals.tstate); 1556 1557 if (!tstate) { 1558 tstate = PyThreadState_New(internals.istate); 1559 #if !defined(NDEBUG) 1560 if (!tstate) 1561 pybind11_fail("scoped_acquire: could not create thread state!"); 1562 #endif 1563 tstate->gilstate_counter = 0; 1564 #if PY_MAJOR_VERSION < 3 1565 PyThread_delete_key_value(internals.tstate); 1566 #endif 1567 PyThread_set_key_value(internals.tstate, tstate); 1568 } else { 1569 release = detail::get_thread_state_unchecked() != tstate; 1570 } 1571 1572 if (release) { 1573 /* Work around an annoying assertion in PyThreadState_Swap */ 1574 #if defined(Py_DEBUG) 1575 PyInterpreterState *interp = tstate->interp; 1576 tstate->interp = nullptr; 1577 #endif 1578 PyEval_AcquireThread(tstate); 1579 #if defined(Py_DEBUG) 1580 tstate->interp = interp; 1581 #endif 1582 } 1583 1584 inc_ref(); 1585 } 1586 1587 void inc_ref() { 1588 ++tstate->gilstate_counter; 1589 } 1590 1591 PYBIND11_NOINLINE void dec_ref() { 1592 --tstate->gilstate_counter; 1593 #if !defined(NDEBUG) 1594 if (detail::get_thread_state_unchecked() != tstate) 1595 pybind11_fail("scoped_acquire::dec_ref(): thread state must be current!"); 1596 if (tstate->gilstate_counter < 0) 1597 pybind11_fail("scoped_acquire::dec_ref(): reference count underflow!"); 1598 #endif 1599 if (tstate->gilstate_counter == 0) { 1600 #if !defined(NDEBUG) 1601 if (!release) 1602 pybind11_fail("scoped_acquire::dec_ref(): internal error!"); 1603 #endif 1604 PyThreadState_Clear(tstate); 1605 PyThreadState_DeleteCurrent(); 1606 PyThread_delete_key_value(detail::get_internals().tstate); 1607 release = false; 1608 } 1609 } 1610 1611 PYBIND11_NOINLINE ~gil_scoped_acquire() { 1612 dec_ref(); 1613 if (release) 1614 PyEval_SaveThread(); 1615 } 1616private: 1617 PyThreadState *tstate = nullptr; 1618 bool release = true; 1619}; 1620 1621class gil_scoped_release { 1622public: 1623 explicit gil_scoped_release(bool disassoc = false) : disassoc(disassoc) { 1624 tstate = PyEval_SaveThread(); 1625 if (disassoc) { 1626 auto key = detail::get_internals().tstate; 1627 #if PY_MAJOR_VERSION < 3 1628 PyThread_delete_key_value(key); 1629 #else 1630 PyThread_set_key_value(key, nullptr); 1631 #endif 1632 } 1633 } 1634 ~gil_scoped_release() { 1635 if (!tstate) 1636 return; 1637 PyEval_RestoreThread(tstate); 1638 if (disassoc) { 1639 auto key = detail::get_internals().tstate; 1640 #if PY_MAJOR_VERSION < 3 1641 PyThread_delete_key_value(key); 1642 #endif 1643 PyThread_set_key_value(key, tstate); 1644 } 1645 } 1646private: 1647 PyThreadState *tstate; 1648 bool disassoc; 1649}; 1650#else 1651class gil_scoped_acquire { }; 1652class gil_scoped_release { }; 1653#endif 1654 1655error_already_set::~error_already_set() { 1656 if (value) { 1657 gil_scoped_acquire gil; 1658 PyErr_Restore(type, value, trace); 1659 PyErr_Clear(); 1660 } 1661} 1662 1663inline function get_type_overload(const void *this_ptr, const detail::type_info *this_type, const char *name) { 1664 handle py_object = detail::get_object_handle(this_ptr, this_type); 1665 if (!py_object) 1666 return function(); 1667 handle type = py_object.get_type(); 1668 auto key = std::make_pair(type.ptr(), name); 1669 1670 /* Cache functions that aren't overloaded in Python to avoid 1671 many costly Python dictionary lookups below */ 1672 auto &cache = detail::get_internals().inactive_overload_cache; 1673 if (cache.find(key) != cache.end()) 1674 return function(); 1675 1676 function overload = getattr(py_object, name, function()); 1677 if (overload.is_cpp_function()) { 1678 cache.insert(key); 1679 return function(); 1680 } 1681 1682 /* Don't call dispatch code if invoked from overridden function */ 1683 PyFrameObject *frame = PyThreadState_Get()->frame; 1684 if (frame && (std::string) str(frame->f_code->co_name) == name && 1685 frame->f_code->co_argcount > 0) { 1686 PyFrame_FastToLocals(frame); 1687 PyObject *self_caller = PyDict_GetItem( 1688 frame->f_locals, PyTuple_GET_ITEM(frame->f_code->co_varnames, 0)); 1689 if (self_caller == py_object.ptr()) 1690 return function(); 1691 } 1692 return overload; 1693} 1694 1695template <class T> function get_overload(const T *this_ptr, const char *name) { 1696 auto tinfo = detail::get_type_info(typeid(T)); 1697 return tinfo ? get_type_overload(this_ptr, tinfo, name) : function(); 1698} 1699 1700#define PYBIND11_OVERLOAD_INT(ret_type, cname, name, ...) { \ 1701 pybind11::gil_scoped_acquire gil; \ 1702 pybind11::function overload = pybind11::get_overload(static_cast<const cname *>(this), name); \ 1703 if (overload) { \ 1704 auto o = overload(__VA_ARGS__); \ 1705 if (pybind11::detail::cast_is_temporary_value_reference<ret_type>::value) { \ 1706 static pybind11::detail::overload_caster_t<ret_type> caster; \ 1707 return pybind11::detail::cast_ref<ret_type>(std::move(o), caster); \ 1708 } \ 1709 else return pybind11::detail::cast_safe<ret_type>(std::move(o)); \ 1710 } \ 1711 } 1712 1713#define PYBIND11_OVERLOAD_NAME(ret_type, cname, name, fn, ...) \ 1714 PYBIND11_OVERLOAD_INT(ret_type, cname, name, __VA_ARGS__) \ 1715 return cname::fn(__VA_ARGS__) 1716 1717#define PYBIND11_OVERLOAD_PURE_NAME(ret_type, cname, name, fn, ...) \ 1718 PYBIND11_OVERLOAD_INT(ret_type, cname, name, __VA_ARGS__) \ 1719 pybind11::pybind11_fail("Tried to call pure virtual function \"" #cname "::" name "\""); 1720 1721#define PYBIND11_OVERLOAD(ret_type, cname, fn, ...) \ 1722 PYBIND11_OVERLOAD_NAME(ret_type, cname, #fn, fn, __VA_ARGS__) 1723 1724#define PYBIND11_OVERLOAD_PURE(ret_type, cname, fn, ...) \ 1725 PYBIND11_OVERLOAD_PURE_NAME(ret_type, cname, #fn, fn, __VA_ARGS__) 1726 1727NAMESPACE_END(pybind11) 1728 1729#if defined(_MSC_VER) 1730# pragma warning(pop) 1731#elif defined(__INTEL_COMPILER) 1732/* Leave ignored warnings on */ 1733#elif defined(__GNUG__) && !defined(__clang__) 1734# pragma GCC diagnostic pop 1735#endif 1736