VBScript passage de tableau par reference
Jeudi 27 mars 2014Comment faire communiquer un Object COM en C++ avec un VBScript :
IDL :
[sourcecode]
library EngineLib
{
dispinterface _IEngineEvents
{
[id(27)] HRESULT MyCallBack( [in,out] VARIANT* arr);
}
}
[/sourcecode]
Le code de l’objet COM C++:
[sourcecode language="cpp"]SAFEARRAY *pSafeArray = ::SafeArrayCreateVector( VT_VARIANT, 0, 1 );
LONG indices = 0 ;
_variant_t v0(L"Hello");
::SafeArrayPutElement( pSafeArray, &indices, &v0 );
VARIANT variant;
VariantInit( &variant );
variant.pparray = &pSafeArray;
variant.vt = VT_BYREF|VT_ARRAY|VT_VARIANT;
CComVariant pVars[1] ;
pVars[0].pvarVal = &variant;
pVars[0].vt = VT_BYREF|VT_VARIANT;
fire( pVars, 1, 27 );
[/sourcecode]
La Fonction fire:
[sourcecode language="cpp"]void fire( CComVariant* pVars, int size, int invoke )
{
CComVariant varResult;
int s = ConnectionPoint.GetSize();
for (int nConnectionIndex=0;nConnectionIndex<s; nConnectionIndex++)
{
CComPtr<IUnknown> sp = m_vec.GetAt(nConnectionIndex);
EXCEPINFO excepinfo ;
IDispatch* pDispatch = reinterpret_cast<IDispatch*>(sp.p);
if ( pDispatch )
{
VariantClear(&varResult);
DISPPARAMS disp = { pVars, NULL, size, 0 };
HRESULT hr = pDispatch->Invoke( invoke, IID_NULL, LOCALE_USER_DEFAULT, DISPATCH_METHOD, &disp, &varResult, &excepinfo, NULL);
}
}
}[/sourcecode]
Le code VBScript:
[sourcecode language="vb"]Function IEngineEvents_MyCallBack( ByRef arr ) ‘Function name is very important
WScript.Echo "arr=" & arr(0)
ReDim Preserve arr(UBound(arr) + 1)
arr(0) = "A1"
arr(1) = "A2"
End Function
Set engine = WScript.CreateObject("MyComComponent", "IEngineEvents_")
‘This function call MyCallBack indirectly
engine.CallCallBack
[/sourcecode]