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
14class VirtClass  {
15public:
16    virtual ~VirtClass() {}
17    virtual void virtual_func() {}
18    virtual void pure_virtual_func() = 0;
19};
20
21class PyVirtClass : public VirtClass {
22    void virtual_func() override {
23        PYBIND11_OVERLOAD(void, VirtClass, virtual_func,);
24    }
25    void pure_virtual_func() override {
26        PYBIND11_OVERLOAD_PURE(void, VirtClass, pure_virtual_func,);
27    }
28};
29
30TEST_SUBMODULE(gil_scoped, m) {
31  py::class_<VirtClass, PyVirtClass>(m, "VirtClass")
32      .def(py::init<>())
33      .def("virtual_func", &VirtClass::virtual_func)
34      .def("pure_virtual_func", &VirtClass::pure_virtual_func);
35
36    m.def("test_callback_py_obj",
37          [](py::object func) { func(); });
38    m.def("test_callback_std_func",
39          [](const std::function<void()> &func) { func(); });
40    m.def("test_callback_virtual_func",
41          [](VirtClass &virt) { virt.virtual_func(); });
42    m.def("test_callback_pure_virtual_func",
43          [](VirtClass &virt) { virt.pure_virtual_func(); });
44    m.def("test_cross_module_gil",
45          []() {
46              auto cm = py::module::import("cross_module_gil_utils");
47              auto gil_acquire = reinterpret_cast<void (*)()>(
48                  PyLong_AsVoidPtr(cm.attr("gil_acquire_funcaddr").ptr()));
49              py::gil_scoped_release gil_release;
50              gil_acquire();
51          });
52}
53