sample.cpp 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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. #include "ChakraCore.h"
  6. #include <stdlib.h>
  7. #include <stdio.h>
  8. #include <string>
  9. #include <cstring>
  10. #define FAIL_CHECK(cmd) \
  11. do \
  12. { \
  13. JsErrorCode errCode = cmd; \
  14. if (errCode != JsNoError) \
  15. { \
  16. printf("Error %d at '%s'\n", \
  17. errCode, #cmd); \
  18. return 1; \
  19. } \
  20. } while(0)
  21. using namespace std;
  22. #ifndef nullptr
  23. #define nullptr 0
  24. #endif
  25. int main()
  26. {
  27. JsRuntimeHandle runtime;
  28. JsContextRef context;
  29. JsValueRef result;
  30. unsigned currentSourceContext = 0;
  31. const char* script = "(()=>{return \'SUCCESS\';})()";
  32. size_t length = strlen(script);
  33. // Create a runtime.
  34. JsCreateRuntime(JsRuntimeAttributeNone, nullptr, &runtime);
  35. // Create an execution context.
  36. JsCreateContext(runtime, &context);
  37. // Now set the current execution context.
  38. JsSetCurrentContext(context);
  39. JsValueRef fname;
  40. FAIL_CHECK(JsCreateString("sample", strlen("sample"), &fname));
  41. JsValueRef scriptSource;
  42. FAIL_CHECK(JsCreateString(script, length, &scriptSource));
  43. // Run the script.
  44. FAIL_CHECK(JsRun(scriptSource, currentSourceContext++, fname,
  45. JsParseScriptAttributeNone, &result));
  46. // Convert your script result to String in JavaScript; redundant if your script returns a String
  47. JsValueRef resultJSString;
  48. FAIL_CHECK(JsConvertValueToString(result, &resultJSString));
  49. // Project script result back to C++.
  50. char *resultSTR = nullptr;
  51. size_t stringLength;
  52. FAIL_CHECK(JsCopyString(resultJSString, nullptr, 0, &stringLength));
  53. resultSTR = (char*)malloc(stringLength + 1);
  54. FAIL_CHECK(JsCopyString(resultJSString, resultSTR, stringLength + 1, nullptr));
  55. resultSTR[stringLength] = 0;
  56. printf("Result -> %s \n", resultSTR);
  57. free(resultSTR);
  58. // Dispose runtime
  59. JsSetCurrentContext(JS_INVALID_REFERENCE);
  60. JsDisposeRuntime(runtime);
  61. return 0;
  62. }