Last active
November 15, 2022 11:14
-
-
Save dpino/6d60903b67a3495cb646e150bd30fb10 to your computer and use it in GitHub Desktop.
Pass CPP object to JavaScript function
This file contains hidden or 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
/** | |
* Pass CPP object to JavaScript function | |
* | |
* sample.js: | |
* function fileInfo(obj) | |
* { | |
* return "fileInfo: " + obj.i; | |
* } | |
* | |
* To compile: g++ main.cc -o main `pkg-config --cflags --libs javascriptcoregtk-4.0` | |
* | |
*/ | |
#include <iostream> | |
#include <string> | |
#include <fstream> | |
#include <streambuf> | |
#include <jsc/jsc.h> | |
using namespace std; | |
class Sample { | |
public: | |
Sample(int i) { this->i = i; }; | |
JSCValue* toJSObject(JSCContext* jsContext); | |
int i; | |
}; | |
JSCValue* Sample::toJSObject(JSCContext* jsContext) | |
{ | |
JSCValue* ret = jsc_value_new_object(jsContext, nullptr, nullptr); | |
JSCValue* i = jsc_value_new_number(jsContext, this->i); | |
jsc_value_object_define_property_data(ret, "i", JSC_VALUE_PROPERTY_ENUMERABLE, i); | |
return ret; | |
} | |
int main(int argc, char* argv[]) | |
{ | |
// Create jsContext. | |
JSCContext* jsContext = jsc_context_new(); | |
// Load JavaScript file. | |
const std::string filename = {"sample.js"}; | |
ifstream t("sample.js"); | |
string code((std::istreambuf_iterator<char>(t)), | |
std::istreambuf_iterator<char>()); | |
JSCValue* ret = jsc_context_evaluate(jsContext, code.c_str(), static_cast<gssize>(code.length())); | |
// Query 'fileInfo' and store it into JSCValue. | |
JSCValue* fileInfo = jsc_context_evaluate(jsContext, "fileInfo", 8); | |
if (!jsc_value_is_function(fileInfo)) { | |
cerr << "Couldn't find function 'fileInfo'" << endl; | |
exit(EXIT_FAILURE); | |
} | |
// Create CPP object. | |
Sample obj(42); | |
// Convert to JSCValue object and call 'fileInfo' function. | |
ret = jsc_value_function_call(fileInfo, JSC_TYPE_VALUE, obj.toJSObject(jsContext), G_TYPE_NONE); | |
cout << "ret: [" << jsc_value_to_string(ret) << "]" << endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment