Skip to content

Instantly share code, notes, and snippets.

Created October 20, 2015 09:42
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/c0e01ac70493ef4cdec5 to your computer and use it in GitHub Desktop.
Save anonymous/c0e01ac70493ef4cdec5 to your computer and use it in GitHub Desktop.
Using C++ as a scripting language
// one of the interfaces the script (DLL) code builds against.
// implemented in the engine runtime.
class ScriptInterface
{
public:
virtual void Foo(void) = 0;
virtual void Bar(void) = 0;
};
// in any of the scripts
class Script
{
public:
void SetEnvironment(ScriptInterface* si)
{
m_interface = si;
}
void Update(void)
{
// can be called by only having a declaration of the interface.
// we don't need to know anything about the concrete implementation of the interface.
m_interface->Foo();
m_interface->Bar();
}
private:
ScriptInterface* m_interface;
};
// export a single C function responsible for creating the script instance
extern "C" __declspec(dllexport) Script* CreateScript(void)
{
Script* instance = new Script;
return instance;
}
// on the engine side of things
class ScriptInterfaceImpl : public ScriptInterface
{
public:
virtual void Foo(void)
{
// do whatever you want here. can use everything from the engine, because this is
// compiled with the engine runtime code.
}
virtual void Bar(void)
{
// same here
}
};
void InstantiateScript(void)
{
// call an exported C function from the DLL to create the script, and set the environment
Script* script = CreateScript();
script->SetEnvironment(new ScriptInterfaceImpl);
}
// somewhere else, run the script every frame
script->Update(deltaTime);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment