js|jscript| function
Call functions in JScript in CPP
The function of calling JScript in C + + is simple, Windows provides a MSScript.ocx control that allows you to manipulate JScript directly: Execute a section of JScript script, or call a specified function. I wrote a simple example:
L Import msscript.ocx. The following instruction generates Msscript.tli and MSSCRIPT.TLH two files in the project directory, with descriptions of all interfaces in MSScript.ocx and the definition of IID.
#import "MSScript.ocx" No_namespace
L declare an object.
Ccomptr<iscriptcontrol> M_iscriptcontrol;
L Create an object instance
if (Succeeded M_iscriptcontrol.cocreateinstance (__uuidof (ScriptControl)))
L set properties such as language.
M_iscriptcontrol->putlanguage (L "JScript");
M_iscriptcontrol->putallowui (VARIANT_FALSE);
L Add JScript code.
M_iscriptcontrol->addcode (L "function test (str1, str2) {return str1 + \"-ok-\ "+ str2;}");
L GET the function, which is to say that the GetItem parameter is 1 to n instead of 0 to n-1.
ccomptr<iscriptprocedurecollection> Aprocedureset = M_iscriptcontrol->getprocedures ();
Long n = aprocedureset->getcount ();
ccomptr<iscriptprocedure> aprocedure = Aprocedureset->getitem (_variant_t (n));
_bstr_t strfunction = Aprocedure->getname ();
l Prepare function parameters.
VARIANT va = {0};
VA.VT = VT_BSTR;
n = 2;
Safearraybound Bounds[1] = {0};
Bounds[0].celements = n;
safearray* PSA = SafeArrayCreate (vt_variant, 1, bounds);
Long i = 0;
for (i = 0; i < n; i++)
{
Va.bstrval = SysAllocString (L "test");
SafeArrayPutElement (PSA, &i, &va);
}
L Call a function.
_variant_t result = M_iscriptcontrol->run (strfunction, &PSA);
L Release parameters.
for (i = 0; i < n; i++)
{
Va.bstrval = SysAllocString (L "test");
Safearraygetelement (PSA, &i, &va);
SysFreeString (Va.bstrval);
}
SafeArrayDestroy (PSA);