sample.cpp 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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. // Test ChakraCore.h is being included by multiple C source files
  23. extern "C"
  24. {
  25. void Dummy1();
  26. void Dummy2();
  27. }
  28. #ifndef nullptr
  29. #define nullptr 0
  30. #endif
  31. int main()
  32. {
  33. Dummy1();
  34. Dummy2();
  35. JsRuntimeHandle runtime;
  36. JsContextRef context;
  37. JsValueRef result;
  38. unsigned currentSourceContext = 0;
  39. const char* script = "(()=>{return \'SUCCESS\';})()";
  40. size_t length = strlen(script);
  41. // Create a runtime.
  42. JsCreateRuntime(JsRuntimeAttributeNone, nullptr, &runtime);
  43. // Create an execution context.
  44. JsCreateContext(runtime, &context);
  45. // Now set the current execution context.
  46. JsSetCurrentContext(context);
  47. JsValueRef fname;
  48. FAIL_CHECK(JsCreateString("sample", strlen("sample"), &fname));
  49. JsValueRef scriptSource;
  50. FAIL_CHECK(JsCreateString(script, length, &scriptSource));
  51. // Run the script.
  52. FAIL_CHECK(JsRun(scriptSource, currentSourceContext++, fname,
  53. JsParseScriptAttributeNone, &result));
  54. // Convert your script result to String in JavaScript; redundant if your script returns a String
  55. JsValueRef resultJSString;
  56. FAIL_CHECK(JsConvertValueToString(result, &resultJSString));
  57. // Project script result back to C++.
  58. char *resultSTR = nullptr;
  59. size_t stringLength;
  60. FAIL_CHECK(JsCopyString(resultJSString, nullptr, 0, &stringLength));
  61. resultSTR = (char*)malloc(stringLength + 1);
  62. FAIL_CHECK(JsCopyString(resultJSString, resultSTR, stringLength, nullptr));
  63. resultSTR[stringLength] = 0;
  64. printf("Result -> %s \n", resultSTR);
  65. free(resultSTR);
  66. // Dispose runtime
  67. JsSetCurrentContext(JS_INVALID_REFERENCE);
  68. JsDisposeRuntime(runtime);
  69. return 0;
  70. }