Clearscript: Pass a javascript to C#

Created on 6 Dec 2017  路  6Comments  路  Source: microsoft/ClearScript

how can i pass a js function to the C# function as a paramter
like:

static void Main(string[] args)
{
var script = "cddd.Callback(function(){cddd.log('dddddd')})";

        var engine = new V8ScriptEngine();

        engine.AddHostObject("cddd", new Cddd());

        engine.Execute(script);

        Console.ReadLine();

}
public class Cddd
{
public void Callback(object callbacl)
{
//at here to call the js function in "callbacl"
}

    public void log(string str)
    {
           //TODO:  Do something
    }

}

the problem is in Callback function , callbacl will is a V8ScriptItem,,but it can't invoke

question

Most helpful comment

@kugarliyifan There's no need to create a delegate. Script objects (including functions) can be used directly from the host via the dynamic type:

C# public void Callback(object callback) { ((dynamic)callback)(); }

All 6 comments

i think i solve it

var s=new HostFunctions().del(callbacl);
s();

@kugarliyifan There's no need to create a delegate. Script objects (including functions) can be used directly from the host via the dynamic type:

C# public void Callback(object callback) { ((dynamic)callback)(); }

thk

another question is
if i use dynamic:

var script3 = "cddd.book=function(data,index,str){cddd.log(data + index + str)}";
var engine = new V8ScriptEngine();
var obj = new Cddd();
engine.AddHostObject("cddd", obj);
engine.Execute(script3);
obj.raise("oooo","111111");


public class Cddd
{
       public object book
        {
            get => eventhand;
            set => eventhand = value;
        }


        public void raise(params object[] args)
        {
            ((dynamic) eventhand)(args);
        }
}

when i don't know how much the callback js function parameter,how can i use dynamic to invoke the function and pass "args" on obj.raise("oooo","111111");

Hi @kugarliyifan,

Unfortunately there's no easy way to pass an argument array via dynamic. Here's an ugly way to do it:

C# // using System.Reflection; public void raise(params object[] args) { ((IReflect)eventhand).InvokeMember("[DISPID=0]", BindingFlags.InvokeMethod, null, null, args, null, null, null); }

We'll try to come up with something better in a future release.

Thanks!

thank!!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

flat-eric147 picture flat-eric147  路  5Comments

drearyrainDeng picture drearyrainDeng  路  3Comments

arthurshayne picture arthurshayne  路  3Comments

JohnLudlow picture JohnLudlow  路  4Comments

Bobris picture Bobris  路  6Comments