Skip to content

Instantly share code, notes, and snippets.

@ftk
Last active September 6, 2021 07:25
Show Gist options
  • Save ftk/3184bd9ab08d753efe6a3470163b2035 to your computer and use it in GitHub Desktop.
Save ftk/3184bd9ab08d753efe6a3470163b2035 to your computer and use it in GitHub Desktop.
quickjspp callback example
#include "quickjspp.hpp"
#include <iostream>
class Event {
public:
int type = 0;
};
class Listener {
public:
void listen( std::function<bool(Event*)> callback ){ // Callback passes event by pointer
Event* event = new Event();
event->type = 1234;
auto res = callback( event );
delete event;
std::cout << "result " << res << std::endl; // This is fine. Prints "result 1"
}
};
int main()
{
qjs::Runtime runtime;
qjs::Context context(runtime);
try
{
// export classes as a module
auto& module = context.addModule("MyModule");
module.class_<Event>( "Event" )
.constructor<>()
.fun<&Event::type>( "type" );
module.class_<Listener>( "Listener" )
.constructor<>()
.fun<&Listener::listen>( "listen" );
module.function("log", [](std::string s) { std::cout << "log: " << s << std::endl; });
// import module
context.eval(R"xxx(
import {Event,Listener,log} from "MyModule";
function assert(b, str)
{
if (b) {
return;
} else {
throw Error("assertion failed: " + str);
}
}
class MyClass extends Listener {
constructor() {
super();
this.listen( this.exampleCallback );
}
exampleCallback( evt ) {
log( evt.type ); // This is wrong. Prints garbage.
// Dumping properties shows evt is actually an empty object { }
return true;
}
}
let mc = new MyClass();
)xxx", "<eval>", JS_EVAL_TYPE_MODULE);
}
catch(qjs::exception)
{
auto exc = context.getException();
std::cerr << (std::string) exc << std::endl;
if((bool) exc["stack"])
std::cerr << (std::string) exc["stack"] << std::endl;
return 1;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment