#include #include #include #include namespace py = pybind11; // 全局解释器持有对象 py::scoped_interpreter* g_python_interpreter = nullptr; // 初始化 Python 解释器 extern "C" __declspec(dllexport) bool InitializePython() { try { if (!g_python_interpreter) { g_python_interpreter = new py::scoped_interpreter(); } return true; } catch (const std::exception& e) { std::cerr << "Failed to initialize Python: " << e.what() << std::endl; return false; } } // 清理 Python 解释器 extern "C" __declspec(dllexport) void FinalizePython() { if (g_python_interpreter) { delete g_python_interpreter; g_python_interpreter = nullptr; } } // 执行 doWork 函数 extern "C" __declspec(dllexport) bool RunConversion(const char* script_path) { try { if (!g_python_interpreter) { std::cerr << "Python interpreter not initialized!" << std::endl; return false; } // 添加脚本路径到 sys.path py::module sys = py::module::import("sys"); py::object path = sys.attr("path"); // 获取脚本目录 std::string script_dir = script_path; size_t last_sep = script_dir.find_last_of("/\\"); if (last_sep != std::string::npos) { script_dir = script_dir.substr(0, last_sep); } // 添加到 sys.path path.attr("insert")(0, script_dir); // 导入脚本模块 py::module script_module = py::module::import("main"); // 调用 doWork 函数 script_module.attr("doWork")(); return true; } catch (const py::error_already_set& e) { std::cerr << "Python error: " << e.what() << std::endl; return false; } catch (const std::exception& e) { std::cerr << "Error: " << e.what() << std::endl; return false; } } // 简单的 C API 封装 PYBIND11_MODULE(uf2touft3, m) { m.doc() = "UFT2 to UFT3 code conversion module"; m.def("initialize", &InitializePython, "Initialize Python interpreter"); m.def("finalize", &FinalizePython, "Finalize Python interpreter"); m.def("run_conversion", &RunConversion, "Run the conversion process", py::arg("script_path")); }