Forked from ftk/gist:3184bd9ab08d753efe6a3470163b2035
Last active
September 6, 2021 07:28
-
-
Save projectitis/b8ab7ee70b3d58fe82731cdd138fc001 to your computer and use it in GitHub Desktop.
quickjspp callback example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include "quickjspp.hpp" | |
#include <iostream> | |
class Event { | |
public: | |
virtual ~Event(){} // Added virtual destructor | |
int type = 0; // This int will now be seen as a double by javascript!! | |
}; | |
class Listener { | |
public: | |
void listen( std::function<bool(Event*)> callback ){ // Callback passes event by pointer | |
Event* event = new Event(); | |
event->type = 105; // Changed to 105 | |
auto res = callback( event ); | |
delete event; | |
std::cout << "result " << res << std::endl; // Prints 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 prints 5.2e-322 (and not 105) | |
// However, 105 in binary is 01101001, which is 5.2e-322 as a double!! | |
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