|
| 1 | +//------------------------------------------------------------------------------------------------------- |
| 2 | +// Copyright (C) Microsoft. All rights reserved. |
| 3 | +// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. |
| 4 | +//------------------------------------------------------------------------------------------------------- |
| 5 | + |
| 6 | +#include "ChakraCore.h" |
| 7 | +#include <stdlib.h> |
| 8 | +#include <stdio.h> |
| 9 | +#include <string> |
| 10 | +#include <cstring> |
| 11 | + |
| 12 | +#define FAIL_CHECK(cmd) \ |
| 13 | + do \ |
| 14 | + { \ |
| 15 | + JsErrorCode errCode = cmd; \ |
| 16 | + if (errCode != JsNoError) \ |
| 17 | + { \ |
| 18 | + printf("Error %d at '%s'\n", \ |
| 19 | + errCode, #cmd); \ |
| 20 | + return 1; \ |
| 21 | + } \ |
| 22 | + } while(0) |
| 23 | + |
| 24 | +using namespace std; |
| 25 | + |
| 26 | +int main() |
| 27 | +{ |
| 28 | + JsRuntimeHandle runtime; |
| 29 | + JsContextRef context; |
| 30 | + JsValueRef result; |
| 31 | + unsigned currentSourceContext = 0; |
| 32 | + |
| 33 | + const char* script = "(()=>{return \'SUCCESS\';})()"; |
| 34 | + size_t length = strlen(script); |
| 35 | + |
| 36 | + // Create a runtime. |
| 37 | + JsCreateRuntime(JsRuntimeAttributeNone, nullptr, &runtime); |
| 38 | + |
| 39 | + // Create an execution context. |
| 40 | + JsCreateContext(runtime, &context); |
| 41 | + |
| 42 | + // Now set the current execution context. |
| 43 | + JsSetCurrentContext(context); |
| 44 | + |
| 45 | + JsValueRef fname; |
| 46 | + FAIL_CHECK(JsCreateString("sample", strlen("sample"), &fname)); |
| 47 | + |
| 48 | + JsValueRef scriptSource; |
| 49 | + FAIL_CHECK(JsCreateString(script, length, &scriptSource)); |
| 50 | + |
| 51 | + // Run the script. |
| 52 | + FAIL_CHECK(JsRun(scriptSource, currentSourceContext++, fname, |
| 53 | + JsParseScriptAttributeNone, &result)); |
| 54 | + |
| 55 | + // Convert your script result to String in JavaScript; redundant if your script returns a String |
| 56 | + JsValueRef resultJSString; |
| 57 | + FAIL_CHECK(JsConvertValueToString(result, &resultJSString)); |
| 58 | + |
| 59 | + // Project script result back to C++. |
| 60 | + uint8_t *resultSTR = nullptr; |
| 61 | + size_t stringLength; |
| 62 | + FAIL_CHECK(JsCopyStringUtf8(resultJSString, nullptr, 0, &stringLength)); |
| 63 | + resultSTR = (uint8_t*)malloc(stringLength + 1); |
| 64 | + FAIL_CHECK(JsCopyStringUtf8(resultJSString, resultSTR, stringLength + 1, nullptr)); |
| 65 | + resultSTR[stringLength] = 0; |
| 66 | + |
| 67 | + printf("Result -> %s \n", resultSTR); |
| 68 | + free(resultSTR); |
| 69 | + |
| 70 | + // Dispose runtime |
| 71 | + JsSetCurrentContext(JS_INVALID_REFERENCE); |
| 72 | + JsDisposeRuntime(runtime); |
| 73 | + |
| 74 | + return 0; |
| 75 | +} |
0 commit comments