Last active
May 24, 2021 22:51
-
-
Save germandiagogomez/b37a6cd8cace0b0a06073af350fa520a to your computer and use it in GitHub Desktop.
Workaround to expose C++ instances in Wren with Wrenbind17
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 1. Create a struct to be able to expose some fields | |
struct ScriptEnv { | |
std::shared_ptr<spdlog::logger> gameLog; | |
Guinyote::View::VideoManager * videoManager; | |
RuntimeConfig const * config; | |
std::string orsAddress; | |
}; | |
// Create a C++ instance to pass the data to wren | |
ScriptEnv scriptEnv{ | |
.gameLog = logger_, | |
.videoManager = i_->videoManager, | |
.config = i_->config, | |
.orsAddress = i_->orsAddress | |
}; | |
// Register in environment module | |
auto & m = vm->module("environment"); | |
// Register ScriptEnv fields, etc. | |
auto & wrenEnvClass = m.klass<ScriptEnv>("ScriptEnv"); | |
// Small nicety via C++17: template do-not-repeat-yourself | |
// auto template parameter for passing members to pointers | |
wrenEnvClass.varReadonly<&ScriptEnv::gameLog>("log"); | |
wrenEnvClass.varReadonly<&ScriptEnv::videoManager>("videoManager"); | |
wrenEnvClass.varReadonly<&ScriptEnv::config>("config"); | |
// Create a Wren global to expose the C++ Script env | |
m.append("var Env = null"); | |
// Emit Wren code for a class that will set Env | |
m.append(R"--(class EnvSetter { | |
static set(env) { | |
Env = env | |
} | |
} | |
)--"); | |
// run the module code | |
vm->runFromSource("environment", m.str()); | |
// Use the set and expose the C++-side variable | |
vm->find("environment", "EnvSetter").func("set(_)")(&scriptEnv); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment