I have found Passing an array from Javascript to C++ solution, but I have another task: Passing an object from Javascript to C++ (if I use IWebBrowser2 with IDispatch)
I mean that I need call C++ method via window.external.method with JavaScript object argument
var obj = {name: "Petr", group: "Friend"};
window.external.myMethod(obj);
How to get access to object member "name", "group", etc. ?
You can access the object's properties via the IDispatch
interface and its methods GetIDsOfNames
and Invoke
.
Depending on your definition of myMethod
, you should be receiving obj
as either a VARIANT
or an IDispatch *
in your C++ code. If a VARIANT
, vt
should be VT_DISPACTH
, in which case you can safely dereference pdispval
.
Once you have an IDispatch
pointer, you can use GetIDsOfNames
to get the DISPID
for a property that you're interested in like so:
_bstr_t sPropertyName = L"myProperty";
DISPID dispid = 0;
HRESULT hr = pDispatch->GetIDsOfNames(IID_NULL, &sPropertyName, 1, LOCALE_SYSTEM_DEFAULT, &dispid);
if(SUCCEEDED(hr))
{
...
Once you have successfully received your DISPID
, you must call Invoke
differently according to whether you would like to get a value, set a value or call a method.
For instance, to get a value:
VARIANT vValue;
hr = pDispatch->Invoke(dispid, IID_NULL, LOCALE_SYSTEM_DEFAULT, DISPATCH_PROPERTYGET, 0, &vValue, 0, 0);
if(SUCCEEDED(hr))
{
...
See the documentation for Invoke
for more information about the different permutations when calling it.