Call functions in Jscript in CPP
Calling Jscript functions in C ++ is very simple. Windows provides a msscript. ocx controls can be used to directly operate Jscript: execute a Jscript or call a specified function. I wrote a simple example:
L import msscript. ocx. The following command generates msscript. tli and msscript. tlh files in the project directory, which contain descriptions of all interfaces in msscript. ocx and 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 language and other attributes.
m_iScriptControl -> PutLanguage (L "JScript" );
m_iScriptControl -> PutAllowUI ( VARIANT_FALSE );
L add the Jscript code.
m_iScriptControl -> AddCode (L "function test(str1, str2) { return str1 + "-ok-" + str2; }" );
L obtain the function. here we need to note that the GetItem parameter is 1 to n, not 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 the 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 );
Original article address:Http://dev.csdn.net/author/absurd/7c6ea0f7f67044eeba924a98278a477a.html