python/src/module.cpp
| Line | Branch | Exec | Source |
|---|---|---|---|
| 1 | // SPDX-License-Identifier: BSD-3-Clause | ||
| 2 | #include <string> | ||
| 3 | #include <vector> | ||
| 4 | |||
| 5 | #include <nanobind/nanobind.h> | ||
| 6 | #include <nanobind/stl/string.h> | ||
| 7 | #include <nanobind/stl/vector.h> | ||
| 8 | |||
| 9 | #include "bindings.h" | ||
| 10 | #include "chrono_batch_render/app/cli.h" | ||
| 11 | #include "chrono_batch_render/stage/store_lock.h" | ||
| 12 | |||
| 13 | #ifdef Py_LIMITED_API | ||
| 14 | #if defined(_WIN32) | ||
| 15 | #include <windows.h> | ||
| 16 | #else | ||
| 17 | #include <dlfcn.h> | ||
| 18 | #endif | ||
| 19 | #endif | ||
| 20 | |||
| 21 | namespace { | ||
| 22 | |||
| 23 | 165 | bool HoldsTheGil() { | |
| 24 | #ifdef Py_LIMITED_API | ||
| 25 | using Check = int (*)(); | ||
| 26 | static const Check check = [] { | ||
| 27 | #if defined(_WIN32) | ||
| 28 | HMODULE python = nullptr; | ||
| 29 | GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | | ||
| 30 | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, | ||
| 31 | reinterpret_cast<LPCWSTR>(&Py_IsInitialized), &python); | ||
| 32 | return python ? reinterpret_cast<Check>(GetProcAddress(python, "PyGILState_Check")) | ||
| 33 | : nullptr; | ||
| 34 | #else | ||
| 35 | return reinterpret_cast<Check>(dlsym(RTLD_DEFAULT, "PyGILState_Check")); | ||
| 36 | #endif | ||
| 37 | }(); | ||
| 38 | return check != nullptr && check() != 0; | ||
| 39 | #else | ||
| 40 | 165 | return PyGILState_Check() != 0; | |
| 41 | #endif | ||
| 42 | } | ||
| 43 | |||
| 44 | 165 | void WaitWithoutTheGil(void (*wait)(void*), void* context) { | |
| 45 | 165 | if (Py_IsInitialized() && HoldsTheGil()) { | |
| 46 | 138 | const nanobind::gil_scoped_release release; | |
| 47 | 138 | wait(context); | |
| 48 | 138 | return; | |
| 49 | 138 | } | |
| 50 | 27 | wait(context); | |
| 51 | } | ||
| 52 | |||
| 53 | } | ||
| 54 | |||
| 55 | 8 | NB_MODULE(_core, module) { | |
| 56 | 2 | module.attr("__version__") = CHRONO_BATCH_RENDER_VERSION; | |
| 57 | 2 | chrono::batch_render::StoreLock::SetBlockingWait(WaitWithoutTheGil); | |
| 58 | 2 | chrono::batch_render::python::BindDevice(module); | |
| 59 | 2 | chrono::batch_render::python::BindScene(module); | |
| 60 | 2 | chrono::batch_render::python::BindRender(module); | |
| 61 | 2 | chrono::batch_render::python::BindSensorPipeline(module); | |
| 62 | 2 | chrono::batch_render::python::BindImport(module); | |
| 63 | 2 | chrono::batch_render::python::BindIo(module); | |
| 64 | 2 | chrono::batch_render::python::BindRotation(module); | |
| 65 | 2 | module.def( | |
| 66 | "run_cli", | ||
| 67 | 2 | [](const std::vector<std::string>& args) { | |
| 68 | const nanobind::gil_scoped_release release; | ||
| 69 | return chrono::batch_render::app::RunCli(args); | ||
| 70 | }, | ||
| 71 | 2 | nanobind::arg("args")); | |
| 72 | 2 | } | |
| 73 |