-
Notifications
You must be signed in to change notification settings - Fork 101
Expand file tree
/
Copy pathexample.cpp
More file actions
65 lines (59 loc) · 1.97 KB
/
Copy pathexample.cpp
File metadata and controls
65 lines (59 loc) · 1.97 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#include "quickjspp.hpp"
#include <iostream>
class MyClass
{
public:
MyClass() {}
MyClass(std::vector<int>) {}
double member_variable = 5.5;
std::string member_function(const std::string& s) { return "Hello, " + s; }
};
void println(qjs::rest<std::string> args) {
for (auto const & arg : args) std::cout << arg << " ";
std::cout << "\n";
}
int main()
{
qjs::Runtime runtime;
qjs::Context context(runtime);
try
{
// export classes as a module
auto& module = context.addModule("MyModule");
module.function<&println>("println");
module.class_<MyClass>("MyClass")
.constructor<>()
.constructor<std::vector<int>>("MyClassA")
.fun<&MyClass::member_variable>("member_variable")
.fun<&MyClass::member_function>("member_function");
// import module
context.eval(R"xxx(
import * as my from 'MyModule';
globalThis.my = my;
)xxx", "<import>", JS_EVAL_TYPE_MODULE);
// evaluate js code
context.eval(R"xxx(
let v1 = new my.MyClass();
v1.member_variable = 1;
let v2 = new my.MyClassA([1,2,3]);
function my_callback(str) {
my.println("at callback:", v2.member_function(str));
}
)xxx");
// callback
auto cb = (std::function<void(const std::string&)>) context.eval("my_callback");
cb("world");
// passing c++ objects to JS
auto lambda = context.eval("x=>my.println(x.member_function('lambda'))").as<std::function<void(qjs::shared_ptr<MyClass>)>>();
auto v3 = qjs::make_shared<MyClass>(context.ctx, std::vector{1,2,3});
lambda(v3);
}
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;
}
}