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, use the VARJUS_DEFINE_CALLBACK
macro. This macro simplifies the process of creating functions that can be called from scripts.
Example
VARJUS_DEFINE_CALLBACK(MyCallback, ctx, args) {
return CStringValue::Construct(ctx->m_pRuntime, std::format("myCallback: {}", args[0]->ValueAsString()));
}
Notes
- Never return
nullptr
from these callbacks, as it can lead to undefined behavior. - Always use the
Construct
methods to allocate values instead of manually allocating them.
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.
Method Declaration
__VARJUS_ND Success AddNewCallback(const VarjusString& name, const Function_t& callback, std::size_t numArgs);
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
UNCHECKED_PARAMETER_COUNT
if you want to allow a variable number of arguments.
- Use
Example
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
.
Example
fn main()
{
// Use the same identifier you registered with state.AddNewCallback
return cppFunc("hello!"); // Output: "myCallback: \"hello!\""
}
Additional Considerations
- Performance: Your code runs in C++ :)
- Error Handling: You can always trust that you receive the same number of arguments as defined in
AddNewCallback
. - Thread Safety: If using callbacks in a multithreaded environment, ensure thread safety where necessary.