Skip to content

Instantly share code, notes, and snippets.

/gist:c0e01ac70493ef4cdec5 Secret

Created Oct 20, 2015
Embed
What would you like to do?
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