Calling C++ Functions
This documentation explains how you can call your own C++ callbacks directly from your Varjus scripts. This feature allows interaction between your script and native C++ code, enabling powerful integrations and optimizations.
Defining the Callback in C++
To define a callback that can be called from a script, use the VARJUS_DEFINE_CALLBACK
macro. This macro simplifies the process by generating the proper function signature expected by the runtime. Here's an example:
VARJUS_DEFINE_CALLBACK(MyCallback, ctx, args) {
return CStringValue::Construct(ctx->m_pRuntime, std::format("myCallback: {}", args[0]->ValueAsString()));
}
It’s important to always use the provided Construct
methods for allocating return values. Manual allocation is discouraged and will result in memory issues. Returning nullptr
is also unsafe and will lead to undefined behavior, so callbacks should always return a valid value.
Registering the Callback in the State
To make your callback available in scripts, you must register it using the AddNewCallback
method of a Varjus::State
instance.
__VARJUS_ND Success AddNewCallback(const VarjusString& name, const Varjus::Function_t& callback, std::size_t numArgs);
Method Parameters
name
- The name of the callback as it will be used in the script.callback
- A reference to your C++ callback function (e.g.,MyCallback
).numArgs
- The expected number of arguments for the callback.- Use
Varjus::UNCHECKED_PARAMETER_COUNT
if you want to allow a variable number of arguments.
- Use
int main()
{
// Create a new execution state
Varjus::State state;
// Register the callback function
// name callback numArgs
if (!state.AddNewCallback("cppFunc", MyCallback, 1)) {
std::cerr << "Failed to register callback!\n";
return 1;
}
// Continue with the rest of the initialization...
}
Calling the Callback from a Script
Once registered, the callback can be invoked from a Varjus script using the name provided in AddNewCallback
.
fn main()
{
// Use the same identifier you registered with state.AddNewCallback
return cppFunc("hello!"); // Output: "myCallback: \"hello!\""
}