Search code examples
c++comwshiactivescript

Executing cscript using IActiveScript with C++


I'm trying to execute a script using cscript with IActiveScriptParse and ParseScriptText but for some reason I get an error: E_UNEXPECTED.

This article has helped me a lot. I'm using its getEngineGuid function in my code.

The code below is what I've tried. It prints:

-2147418113
-2147418113

Meaning activeScriptParse->ParseScriptText returns E_UNEXPECTED. So what am I doing wrong?

#include <iostream>
#include <Windows.h>
#include <ObjBase.h>
#include <ActivScp.h>

using namespace std;

int main(int argc, char* argv[])
{
    CoInitialize(NULL);
    GUID guidBuffer;

    // Find the script engine to use for files that end with a .js extension.
    // This is implemented in the article I linked to.
    getEngineGuid(".js", &guidBuffer);

    IActiveScript *activeScript;
    CoCreateInstance(guidBuffer, 0, CLSCTX_ALL,
                     IID_IActiveScript,
                     (void **)&activeScript);
    IActiveScriptParse *activeScriptParse;
    activeScript->QueryInterface(IID_IActiveScriptParse,
                                 (void **)&activeScriptParse);
    activeScriptParse->InitNew();

    EXCEPINFO ei ={};
    VARIANT result;
    cout << E_UNEXPECTED << endl;
    cout << activeScriptParse->ParseScriptText(OLESTR("(new Date()).getTime()"), NULL,
                                               NULL, NULL, 0, 0, SCRIPTTEXT_ISEXPRESSION,
                                               &result, &ei) << endl;
    activeScriptParse->Release();

    return 0;
}

Thanks a lot!


Solution

  • Igor Tandetnik's comment pointed me to the correct direction.

    The article I used shows how to SetScriptSite but it's written in c. This question: How to load & call a VBScript function from within C++ has a very helpful answer.

    As that answer says, what you should do is define a class that has at least IActiveScriptSite and IActiveScriptSiteWindow as interfaces.