Created
October 2, 2016 19:17
-
-
Save ptomato/ba3cb438398ab56e35040a84b3f7f683 to your computer and use it in GitHub Desktop.
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
// compile me with: | |
// g++ -g -O0 -o testconv testconv.cpp `pkg-config --cflags --libs mozjs-24` -std=c++11 | |
// output: | |
// JS_ValueToInt32: did not convert | |
// JS::ToInt32: converted, value is 0 | |
#include <iostream> | |
#include <jsapi.h> | |
static JSClass global_class = { | |
"global", JSCLASS_GLOBAL_FLAGS, | |
JS_PropertyStub, JS_DeletePropertyStub, JS_PropertyStub, | |
JS_StrictPropertyStub, JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub | |
}; | |
static void | |
define_element(JSContext *cx, JS::HandleObject array_obj, const char *text) | |
{ | |
JS::RootedString message(cx, JS_NewStringCopyZ(cx, text)); | |
JS::RootedValue val(cx, JS::StringValue(message)); | |
JS_DefineElement(cx, array_obj, 0, val, nullptr, nullptr, 0); | |
} | |
static void | |
print_results(const char *routine, bool worked, int32_t intval) | |
{ | |
std::cout << routine << ": "; | |
if (worked) | |
std::cout << "converted, value is " << intval; | |
else | |
std::cout << "did not convert"; | |
std::cout << std::endl; | |
} | |
int | |
main(void) | |
{ | |
JSRuntime *rt = JS_NewRuntime(8L * 1024 * 1024, JS_USE_HELPER_THREADS); | |
if (!rt) return 1; | |
JSContext *cx = JS_NewContext(rt, 8192); | |
if (!cx) return 1; | |
{ | |
JSAutoRequest ar(cx); | |
JS::RootedObject global(cx, | |
JS_NewGlobalObject(cx, &global_class, nullptr)); | |
if (!global) return 1; | |
{ | |
JSAutoCompartment ac(cx, global); | |
if (!JS_InitStandardClasses(cx, global)) return 1; | |
JS::RootedObject array_obj(cx, JS_NewArrayObject(cx, 0, nullptr)); | |
define_element(cx, array_obj, "this"); | |
define_element(cx, array_obj, "is"); | |
define_element(cx, array_obj, "fine"); | |
JS::RootedValue array(cx, JS::ObjectValue(*array_obj)); | |
int32_t intval; | |
bool worked = JS_ValueToInt32(cx, array, &intval); | |
print_results("JS_ValueToInt32", worked, intval); | |
worked = JS::ToInt32(cx, array, &intval); | |
print_results("JS::ToInt32", worked, intval); | |
} | |
} | |
JS_DestroyContext(cx); | |
JS_DestroyRuntime(rt); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment