cross_module_gil_utils.cpp 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /*
  2. tests/cross_module_gil_utils.cpp -- tools for acquiring GIL from a different module
  3. Copyright (c) 2019 Google LLC
  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. #include <pybind11/pybind11.h>
  8. #include <cstdint>
  9. // This file mimics a DSO that makes pybind11 calls but does not define a
  10. // PYBIND11_MODULE. The purpose is to test that such a DSO can create a
  11. // py::gil_scoped_acquire when the running thread is in a GIL-released state.
  12. //
  13. // Note that we define a Python module here for convenience, but in general
  14. // this need not be the case. The typical scenario would be a DSO that implements
  15. // shared logic used internally by multiple pybind11 modules.
  16. namespace {
  17. namespace py = pybind11;
  18. void gil_acquire() { py::gil_scoped_acquire gil; }
  19. constexpr char kModuleName[] = "cross_module_gil_utils";
  20. #if PY_MAJOR_VERSION >= 3
  21. struct PyModuleDef moduledef = {
  22. PyModuleDef_HEAD_INIT,
  23. kModuleName,
  24. NULL,
  25. 0,
  26. NULL,
  27. NULL,
  28. NULL,
  29. NULL,
  30. NULL
  31. };
  32. #else
  33. PyMethodDef module_methods[] = {
  34. {NULL, NULL, 0, NULL}
  35. };
  36. #endif
  37. } // namespace
  38. extern "C" PYBIND11_EXPORT
  39. #if PY_MAJOR_VERSION >= 3
  40. PyObject* PyInit_cross_module_gil_utils()
  41. #else
  42. void initcross_module_gil_utils()
  43. #endif
  44. {
  45. PyObject* m =
  46. #if PY_MAJOR_VERSION >= 3
  47. PyModule_Create(&moduledef);
  48. #else
  49. Py_InitModule(kModuleName, module_methods);
  50. #endif
  51. if (m != NULL) {
  52. static_assert(
  53. sizeof(&gil_acquire) == sizeof(void*),
  54. "Function pointer must have the same size as void*");
  55. PyModule_AddObject(m, "gil_acquire_funcaddr",
  56. PyLong_FromVoidPtr(reinterpret_cast<void*>(&gil_acquire)));
  57. }
  58. #if PY_MAJOR_VERSION >= 3
  59. return m;
  60. #endif
  61. }