Created
March 17, 2025 14:56
-
-
Save lxfly2000/f2554cb95056007b95f3b7b58d8c64d0 to your computer and use it in GitHub Desktop.
VC++ and JS interop using Chakra
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
#include<Windows.h> | |
#include<jsrt.h> | |
#pragma comment(lib,"jsrt.lib") | |
int WINAPI wWinMain(_In_ HINSTANCE hInst, _In_opt_ HINSTANCE hPrevInst, _In_ LPWSTR param, _In_ int iSW) | |
{ | |
JsRuntimeHandle runtime; | |
JsContextRef context; | |
JsValueRef result; | |
unsigned currentSourceContext = 0; | |
// Your script; try replace hello-world with something else | |
const TCHAR script[] = L"(function(){return \"Hello\";})()"; | |
// Create a runtime. | |
JsCreateRuntime(JsRuntimeAttributeNone,JsRuntimeVersion11, nullptr, &runtime); | |
// Create an execution context. | |
JsCreateContext(runtime,nullptr, &context); | |
// Now set the current execution context. | |
JsSetCurrentContext(context); | |
// Run the script. | |
JsErrorCode e = JsRunScript(script, currentSourceContext++, L"", &result); | |
if (e) | |
return 1; | |
// Convert your script result to String in JavaScript; redundant if your script returns a String | |
JsValueRef resultJSString; | |
JsConvertValueToString(result, &resultJSString); | |
// Project script result back to C++. | |
const wchar_t* resultWC; | |
size_t stringLength; | |
JsStringToPointer(resultJSString, &resultWC, &stringLength); | |
MessageBox(NULL, resultWC, NULL, MB_ICONINFORMATION); | |
// Dispose runtime | |
JsSetCurrentContext(JS_INVALID_REFERENCE); | |
JsDisposeRuntime(runtime); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment