Use Methods On C# (Sharp) Object

Oct 15, 2013 at 7:09 PM
I need to pass in a C# object and call methods on the object. How would I do this?

This is what I've tried.

I get a Jint.Native.JsException -- "Method isn't defined: log".

Any ideas? Thanx in advance.
    public class MyDebugClass
    {
        public void log(string s)
        {
            Debug.Log("JS: "+s);    //write to console
        }
    }

    public void testJS()
    {
        string rules = "testdebug.log(\"hi from script\");";
        
        m_js=new JintEngine();
        
        m_js.SetObjParameter("testdebug", new MyDebugClass());

        try
        {
            m_js.Run(rules);
        }
        catch (Jint.JintException e)
        {
            Debug.LogError("rules.js JintEngine Exception: "+e.ToString ());
        }
        catch (Jint.Native.JsException e)
        {
            Debug.LogError("rules.js Javascript Exception: "+e.ToString ());
        }
    }
And I added this method to JintEngine
        public JintEngine SetObjParameter(string name, object val)
        {
            visitor.GlobalScope[name] = visitor.Global.ObjectClass.New(val);
            return this;
        }
Oct 15, 2013 at 11:09 PM
Did you try just

m_js.SetParameter("testdebug", new MyDebugClass());

?
Oct 15, 2013 at 11:22 PM
That won't compile.

The best overloaded method match for `Jint.JintEngine.SetParameter(string, System.DateTime)' has some invalid arguments.

Thanx.
Oct 15, 2013 at 11:27 PM
Here is what I got to work. Is there a better more generic way?
        public JintEngine SetObjParameter(string name, object val)
        {
            Jint.Native.JsObjectConstructor jsObjConstructor = visitor.Global.ObjectClass;
            jsObjConstructor.PrototypeProperty.DefineOwnProperty("log", visitor.Global.FunctionClass.New<JsDictionaryObject>(logImpl), Jint.Native.PropertyAttributes.DontEnum);
            
            JsObject jsObj = jsObjConstructor.New(val);
            visitor.GlobalScope[name] = jsObj;
            
            return this;
        }

        public JsInstance logImpl(JsDictionaryObject target, JsInstance[] parameters) {
            MethodInfo method = target.Value.GetType().GetMethod("log");
            method.Invoke(target.Value, new object[] { parameters[0].Value });
            return target;
        }
Oct 16, 2013 at 3:19 AM
Are you sure you're using the latest version? Mine has
    public JintEngine SetParameter(string name, object value) {
        visitor.GlobalScope[name] = visitor.Global.WrapClr(value);
        return this;
    }
Which allows you to do what I suggested above.
Marked as answer by sdermanffs on 10/16/2013 at 10:21 AM
Oct 16, 2013 at 7:00 PM
Thank you, we are using an older version with Unity. My workaround will work for my case, if I need more, I'll look into updating to the newer Jint.
Oct 16, 2013 at 7:12 PM
How are you using Jint with Unity, I am interested in the scenario here.
Oct 16, 2013 at 9:36 PM