The example in this tutorial
For our tutorial, we're going to be sandboxing a small application that uses a
library called mylib
.
Our example library
mylib
declares four functions in mylib.h:
#pragma once
#ifdef __cplusplus
extern "C" {
#endif
void hello();
unsigned int add(unsigned int, unsigned int);
void echo(const char* str);
void call_cb(void (*cb) (const char* str));
#ifdef __cplusplus
}
#endif
And implements those function in mylib.c:
#include <stdio.h>
#include "mylib.h"
void hello() {
printf("Hello from mylib\n");
}
unsigned int add(unsigned int a, unsigned int b) {
return a + b;
}
void echo(const char* str) {
printf("echo: %s\n", str);
}
void call_cb(void (*cb) (const char* str)) {
cb("hi again!");
}
While this library is very simple, it will allow us to exercise key features of RLBox including: calling functions, copying strings into the sandbox, registering and handling callbacks from the library in the next chapters.
Our example application
The main application in main.cpp simply invokes each of these functions in turn.
#include <stdio.h>
#include <stdlib.h>
#define release_assert(cond, msg) if (!(cond)) { fputs(msg "\n", stderr); abort(); }
#include "mylib.h"
using namespace std;
// Declare callback function that's going to be invoked from the library.
void hello_cb(const char* str);
int main(int argc, char const *argv[]) {
// Call the library hello function
hello();
int array[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
// Call the library add function
auto ret = add(3, 4);
auto array_val = array[ret];
printf("Got array value %d\n", ret);
// Call the library echo function
const char* helloStr = "hi hi!";
echo(helloStr);
// Call the library function call_cb, passing in the callback hello_cb
call_cb(hello_cb);
return 0;
}
void hello_cb(const char* str)
{
release_assert(str != nullptr, "Expected value for string");
printf("hello_cb: %s\n", str);
}
To build this example on your machine, run the following commands
cd rlbox-book/src/examples/hello-example
cmake -S . -B ./build -DCMAKE_BUILD_TYPE=Debug
cmake --build ./build --config Debug --parallel
Then run it to make sure everything is working.
./build/main
You should see the following output:
Hello from mylib
Got array value 7
echo: hi hi!
hello_cb: hi again!