From 58ef5f9e7d9b354e31b80034f392795ddc509245 Mon Sep 17 00:00:00 2001 From: aozhiwei Date: Sat, 18 Aug 2018 11:08:30 +0800 Subject: [PATCH] add scriptengine.* --- cpp/scriptengine.cc | 84 +++++++++++++++++++++++++++++++++++++++++++++ cpp/scriptengine.h | 30 ++++++++++++++++ 2 files changed, 114 insertions(+) create mode 100644 cpp/scriptengine.cc create mode 100644 cpp/scriptengine.h diff --git a/cpp/scriptengine.cc b/cpp/scriptengine.cc new file mode 100644 index 0000000..a28d01d --- /dev/null +++ b/cpp/scriptengine.cc @@ -0,0 +1,84 @@ +#include +#include +#include + +#include "scriptengine.h" + +void ScriptEngine::Init() +{ + engine_ = new a8::PyEngine(); + engine_->work_path = "pyscript/"; + engine_->Init(); + if (!engine_->IsInitialized()) { + abort(); + } +} + +void ScriptEngine::UnInit() +{ + engine_->UnInit(); + delete engine_; + engine_ = nullptr; +} + +void ScriptEngine::Update() +{ +} + +bool ScriptEngine::LoadModule(const std::string& module_name) +{ + bool ret = engine_->LoadModule(module_name.c_str()); + if (!ret) { + a8::UdpLog::Instance()->Warning("load python module %s error %s\n", + { + module_name, + engine_->GetLastError() + }); + assert(false); + } + return ret; +} + +bool ScriptEngine::LoadString(const std::string& str) +{ + bool ret = engine_->ExecString(str.c_str()); + if (!ret) { + a8::UdpLog::Instance()->Warning("load python string %s error %s", + { + str, + engine_->GetLastError() + }); + assert(false); + } + return ret; +} + +std::tuple ScriptEngine::CallGlobalFunc(const char* func_name, + std::initializer_list args) +{ + auto ret = engine_->CallGlobalFunc(func_name, args); + if (!std::get<0>(ret)) { + a8::UdpLog::Instance()->Warning("call global function %s error %s", + { + func_name, + engine_->GetLastError() + }); + } + return ret; +} + +std::tuple ScriptEngine::CallModuleFunc(const char* module_name, + const char* func_name, + std::initializer_list args) +{ + auto ret = engine_->CallModuleFunc(module_name, func_name, args); + if (!std::get<0>(ret)) { + a8::UdpLog::Instance()->Warning("call module function [%s] %s error %s", + { + module_name, + func_name, + engine_->GetLastError() + }); + } + return ret; +} diff --git a/cpp/scriptengine.h b/cpp/scriptengine.h new file mode 100644 index 0000000..2f4d427 --- /dev/null +++ b/cpp/scriptengine.h @@ -0,0 +1,30 @@ +#pragma once + +namespace a8 +{ + class PyEngine; +}; + +class ScriptEngine : public a8::Singleton +{ + private: + ScriptEngine() {}; + friend class a8::Singleton; + + public: + void Init(); + void UnInit(); + void Update(); + + bool LoadModule(const std::string& module_name); + bool LoadString(const std::string& str); + std::tuple CallGlobalFunc(const char* func_name, + std::initializer_list args); + std::tuple CallModuleFunc(const char* module_name, + const char* func_name, + std::initializer_list args); + + private: + a8::PyEngine *engine_ = nullptr; + +};