Passing a C# class instance back to managed code from JavaScript via COM

对着背影说爱祢 提交于 2019-12-05 05:09:07

How interesting. When we receive the oGizmo object back in doSomethingWith, it is of the type Windows Runtime Object. This behavior is consistent between JavaScript and VBScript.

Now, if we explicitly specify MarshalAs(UnmanagedType.IUnknown) on the return value of the GiveMeAGizmo() method, everything works fine, the object can be cast back to Gizmo inside doSomethingWith:

[ComVisible(true), ClassInterface(ClassInterfaceType.AutoDispatch)]
public class ObjectForScripting
{
    [return: MarshalAs(UnmanagedType.IUnknown)]
    public object GiveMeAGizmo()
    {
        return new Gizmo();
    }

    public object GiveMeAGizmoUser()
    {
        return new GizmoUser();
    }
}

Still, if we specify UnmanagedType.IDispatch or UnmanagedType.Struct (the default one which marshals the object as COM VARIANT), the problem is back.

Thus, there's a workaround, but no reasonable explanation for such COM interop behavior, so far.

[UPDATE] A few more experiments, below. Note how obtaining gizmo1 is successful, while gizmo2 is not:

C#:

// pass a Gizmo object to JavaScript
this.webBrowser.Document.InvokeScript("SetGizmo", new Object[] { new Gizmo()});

// get it back, this works
var gizmo1 = (Gizmo)this.webBrowser.Document.InvokeScript("GetGizmo");

// get a new Gizmo, via window.external.GiveMeAGizmo()
// this fails
var gizmo2 = (Gizmo)this.webBrowser.Document.InvokeScript("GetGizmo2");

JavaScript:

var _gizmo;

function SetGizmo(gizmo) { _gizmo = gizmo; }

function GetGizmo() { return _gizmo; }

function GetGizmo2() { return window.external.GiveMeAGizmo(); }

It's only a guess, but I think such behavior might have something to do with .NET security permission sets, imposed by WebBrowser.ObjectForScripting.

You need to do two things

  1. Find out the type of object as described here.

  2. Extract the actual object outta it using Marshal.GetObjectForIUnknown (read till the end, there is an interface to implement).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!