cross_module_gil_utils.cpp 1.74 KB
Newer Older
1
2
3
4
5
6
7
8
9
/*
    tests/cross_module_gil_utils.cpp -- tools for acquiring GIL from a different module

    Copyright (c) 2019 Google LLC

    All rights reserved. Use of this source code is governed by a
    BSD-style license that can be found in the LICENSE file.
*/
#include <pybind11/pybind11.h>
10

11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <cstdint>

// This file mimics a DSO that makes pybind11 calls but does not define a
// PYBIND11_MODULE. The purpose is to test that such a DSO can create a
// py::gil_scoped_acquire when the running thread is in a GIL-released state.
//
// Note that we define a Python module here for convenience, but in general
// this need not be the case. The typical scenario would be a DSO that implements
// shared logic used internally by multiple pybind11 modules.

namespace {

namespace py = pybind11;
void gil_acquire() { py::gil_scoped_acquire gil; }

constexpr char kModuleName[] = "cross_module_gil_utils";

#if PY_MAJOR_VERSION >= 3
29
30
struct PyModuleDef moduledef
    = {PyModuleDef_HEAD_INIT, kModuleName, NULL, 0, NULL, NULL, NULL, NULL, NULL};
31
#else
32
PyMethodDef module_methods[] = {{NULL, NULL, 0, NULL}};
33
34
#endif

35
} // namespace
36
37
38

extern "C" PYBIND11_EXPORT
#if PY_MAJOR_VERSION >= 3
39
40
    PyObject *
    PyInit_cross_module_gil_utils()
41
#else
42
43
    void
    initcross_module_gil_utils()
44
45
46
#endif
{

47
    PyObject *m =
48
49
50
51
52
53
54
#if PY_MAJOR_VERSION >= 3
        PyModule_Create(&moduledef);
#else
        Py_InitModule(kModuleName, module_methods);
#endif

    if (m != NULL) {
55
56
57
58
        static_assert(sizeof(&gil_acquire) == sizeof(void *),
                      "Function pointer must have the same size as void*");
        PyModule_AddObject(
            m, "gil_acquire_funcaddr", PyLong_FromVoidPtr(reinterpret_cast<void *>(&gil_acquire)));
59
60
61
62
63
64
    }

#if PY_MAJOR_VERSION >= 3
    return m;
#endif
}