Skip to content

Instantly share code, notes, and snippets.

@lxfly2000
Created March 17, 2025 14:56
Show Gist options
  • Save lxfly2000/f2554cb95056007b95f3b7b58d8c64d0 to your computer and use it in GitHub Desktop.
Save lxfly2000/f2554cb95056007b95f3b7b58d8c64d0 to your computer and use it in GitHub Desktop.

Revisions

  1. lxfly2000 created this gist Mar 17, 2025.
    43 changes: 43 additions & 0 deletions jstest.cpp
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,43 @@
    #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;
    }