cross_module_interleaved_error_already_set.cpp
Go to the documentation of this file.
1 /*
2  Copyright (c) 2022 Google LLC
3 
4  All rights reserved. Use of this source code is governed by a
5  BSD-style license that can be found in the LICENSE file.
6 */
7 
8 #include <pybind11/pybind11.h>
9 
10 // This file mimics a DSO that makes pybind11 calls but does not define a PYBIND11_MODULE,
11 // so that the first call of cross_module_error_already_set() triggers the first call of
12 // pybind11::detail::get_internals().
13 
14 namespace {
15 
16 namespace py = pybind11;
17 
18 void interleaved_error_already_set() {
19  py::set_error(PyExc_RuntimeError, "1st error.");
20  try {
21  throw py::error_already_set();
22  } catch (const py::error_already_set &) {
23  // The 2nd error could be conditional in a real application.
24  py::set_error(PyExc_RuntimeError, "2nd error.");
25  } // Here the 1st error is destroyed before the 2nd error is fetched.
26  // The error_already_set dtor triggers a pybind11::detail::get_internals()
27  // call via pybind11::gil_scoped_acquire.
28  if (PyErr_Occurred()) {
29  throw py::error_already_set();
30  }
31 }
32 
33 constexpr char kModuleName[] = "cross_module_interleaved_error_already_set";
34 
35 struct PyModuleDef moduledef = {
36  PyModuleDef_HEAD_INIT, kModuleName, nullptr, 0, nullptr, nullptr, nullptr, nullptr, nullptr};
37 
38 } // namespace
39 
41  PyObject *m = PyModule_Create(&moduledef);
42  if (m != nullptr) {
43  static_assert(sizeof(&interleaved_error_already_set) == sizeof(void *),
44  "Function pointer must have the same size as void *");
45 #ifdef Py_GIL_DISABLED
46  PyUnstable_Module_SetGIL(m, Py_MOD_GIL_NOT_USED);
47 #endif
48  PyModule_AddObject(
49  m,
50  "funcaddr",
51  PyLong_FromVoidPtr(reinterpret_cast<void *>(&interleaved_error_already_set)));
52  }
53  return m;
54 }
m
Matrix3f m
Definition: AngleAxis_mimic_euler.cpp:1
set_error
void set_error(const handle &type, const char *message)
Definition: pytypes.h:346
pybind11.h
PyInit_cross_module_interleaved_error_already_set
PYBIND11_EXPORT PyObject * PyInit_cross_module_interleaved_error_already_set()
Definition: cross_module_interleaved_error_already_set.cpp:40
PYBIND11_EXPORT
#define PYBIND11_EXPORT
Definition: wrap/pybind11/include/pybind11/detail/common.h:163
pybind11
Definition: wrap/pybind11/pybind11/__init__.py:1


gtsam
Author(s):
autogenerated on Sun Dec 22 2024 04:11:22