#pragma once // Shared embedded-interpreter bootstrap for slic3rutils tests that need a live Python // interpreter (test_plugin_host_api.cpp, test_slicing_pipeline_bindings.cpp, ...). // // The runtime is process-wide: once initialized it stays up for the rest of the test process. // CPython cannot be reinitialized after Py_Finalize (a second init aborts inside _datetime), and // the app likewise finalizes it only at exit, so nothing here tears it down. // slic3rutils_tests_main.cpp finalizes the production interpreter once, after the last test case. // // This bootstrap is separate from PythonInterpreter's runtime: whichever of the two brings Python // up first in a process owns it, and the other cannot initialize it again. ctest runs one case per // process, so that only matters if the binary is run directly. #include #include #include #include #include #include #include #include #include #include namespace { void ensure_python_initialized() { if (Py_IsInitialized()) return; static std::unique_ptr interpreter; PyConfig config; PyConfig_InitPythonConfig(&config); config.parse_argv = 0; const auto python_home = boost::dll::program_location().parent_path() / "python"; #ifdef _WIN32 const auto stdlib = python_home / "Lib"; #else const auto stdlib = python_home / "lib" / ("python" + std::to_string(PY_MAJOR_VERSION) + "." + std::to_string(PY_MINOR_VERSION)); #endif // Only a real runtime: a stray python/ folder (packages a test left behind) is not a home. if (boost::filesystem::exists(stdlib / "encodings")) { const std::string home = python_home.string(); const PyStatus status = PyConfig_SetBytesString(&config, &config.home, home.c_str()); if (PyStatus_Exception(status)) { const char* message = status.err_msg ? status.err_msg : "Failed to set Python home"; PyConfig_Clear(&config); throw std::runtime_error(message); } } interpreter = std::make_unique(&config); } pybind11::module_ import_orca_module() { ensure_python_initialized(); // Force PythonPluginBridge.cpp into the test binary so the embedded // PYBIND11_EMBEDDED_MODULE(orca, ...) registration is available. (void) Slic3r::PythonPluginBridge::instance(); return pybind11::module_::import("orca"); } } // namespace