1 /*
2     tests/test_gil_scoped.cpp -- acquire and release gil
3 
4     Copyright (c) 2017 Borja Zarco (Google LLC) <bzarco@google.com>
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 #include "pybind11_tests.h"
11 #include <pybind11/functional.h>
12 
13 
14 class VirtClass  {
15 public:
16     virtual ~VirtClass() = default;
17     VirtClass() = default;
18     VirtClass(const VirtClass&) = delete;
virtual_func()19     virtual void virtual_func() {}
20     virtual void pure_virtual_func() = 0;
21 };
22 
23 class PyVirtClass : public VirtClass {
virtual_func()24     void virtual_func() override {
25         PYBIND11_OVERRIDE(void, VirtClass, virtual_func,);
26     }
pure_virtual_func()27     void pure_virtual_func() override {
28         PYBIND11_OVERRIDE_PURE(void, VirtClass, pure_virtual_func,);
29     }
30 };
31 
TEST_SUBMODULE(gil_scoped,m)32 TEST_SUBMODULE(gil_scoped, m) {
33   py::class_<VirtClass, PyVirtClass>(m, "VirtClass")
34       .def(py::init<>())
35       .def("virtual_func", &VirtClass::virtual_func)
36       .def("pure_virtual_func", &VirtClass::pure_virtual_func);
37 
38     m.def("test_callback_py_obj",
39           [](py::object func) { func(); });
40     m.def("test_callback_std_func",
41           [](const std::function<void()> &func) { func(); });
42     m.def("test_callback_virtual_func",
43           [](VirtClass &virt) { virt.virtual_func(); });
44     m.def("test_callback_pure_virtual_func",
45           [](VirtClass &virt) { virt.pure_virtual_func(); });
46     m.def("test_cross_module_gil",
47           []() {
48               auto cm = py::module_::import("cross_module_gil_utils");
49               auto gil_acquire = reinterpret_cast<void (*)()>(
50                   PyLong_AsVoidPtr(cm.attr("gil_acquire_funcaddr").ptr()));
51               py::gil_scoped_release gil_release;
52               gil_acquire();
53           });
54 }
55