public override void Dispose()
        {
            if (_disposedFlag.Set())
            {
                lock (_executionSynchronizer)
                {
                    if (_jsContext != null)
                    {
                        _jsContext.Dispose();
                        _jsContext = null;
                    }

                    if (_jsEngine != null)
                    {
                        _jsEngine.Dispose();
                        _jsEngine = null;
                    }

                    if (_hostItems != null)
                    {
                        _hostItems.Clear();
                    }
                }
            }
        }
Exemplo n.º 2
0
        internal JsContext(int id, JsEngine engine, IntPtr engineHandle, Action<int> notifyDispose)
        {
            _id = id;
            _engine = engine;
            _notifyDispose = notifyDispose;

            _keepalives = new KeepAliveDictionaryStore();
            _context = jscontext_new(id, engineHandle);
            _convert = new JsConvert(this);
        }
Exemplo n.º 3
0
        public JsObject(JsEngine engine, IntPtr ptr)
        {
            if (engine == null)
                throw new ArgumentNullException("engine");
            if (ptr == IntPtr.Zero)
                throw new ArgumentException("can't wrap an empty object (ptr is Zero)", "ptr");

            _engine = engine;
            _handle = ptr;
        }
Exemplo n.º 4
0
 public static void Main(string[] args)
 {
     using (JsEngine js = new JsEngine()) {
         for (int i=0 ; i < 10 ; i++) {
             js.SetVariable("a", new Simple { N = i, S = (i*10).ToString() });
             Console.WriteLine(js.Execute("a.N+' '+a.S"));
         }
         Console.WriteLine(js.Execute("a.N+' '+a.X"));
     }
 }
Exemplo n.º 5
0
        internal JsScript(int id, JsEngine engine, IntPtr engineHandle, JsConvert convert, string code, string name, Action<int> notifyDispose)
        {
            _id = id;
            _engine = engine;
            _notifyDispose = notifyDispose;

            _script = jsscript_new(engineHandle);

            JsValue v = jsscript_compile(_script, code, name);
            object res = convert.FromJsValue(v);
            Exception e = res as JsException;
            if (e != null) {
                throw e;
            }
        }
        /// <summary>
        /// Constructs an instance of adapter for the Vroom JS engine
        /// (cross-platform bridge to the V8 JS engine)
        /// </summary>
        /// <param name="settings">Settings of the Vroom JS engine</param>
        public EFFCVroomJsEngine(EFFCVroomSettings settings)
        {
            EFFCVroomSettings vroomSettings = settings ?? new EFFCVroomSettings();

            try
            {
                _jsEngine = new OriginalJsEngine(vroomSettings.MaxYoungSpaceSize,
                                                 vroomSettings.MaxOldSpaceSize);
                _jsContext = _jsEngine.CreateContext();
            }
            catch (Exception e)
            {
                throw new JsEngineLoadException(
                          string.Format(CoreStrings.Runtime_JsEngineNotLoaded,
                                        EngineName, e.Message), EngineName, EngineVersion, e);
            }
        }
Exemplo n.º 7
0
        internal JsScript(int id, JsEngine engine, HandleRef engineHandle, JsConvert convert, string code, string name, Action<int> notifyDispose)
        {
            _id = id;
            _engine = engine;
            _notifyDispose = notifyDispose;

            _script = new HandleRef(this, jsscript_new(engineHandle));

            IntPtr v2 = jsscript_compile(_script, code, name);
            //JsValue v = jsscript_compile(_script, code, name);

            //object res = convert.FromJsValue(v);
            //Exception e = res as JsException;
            //if (e != null)
            //{
            //    throw e;
            //}
        }
Exemplo n.º 8
0
        public static void Main(string[] args)
        {
            AssemblyLoader.EnsureLoaded();

            while (true)
            {
                using (JsEngine js = new JsEngine(4, 32))
                {
                    using (JsContext context = js.CreateContext())
                    {
                        // Create a global variable on the JS side.
                        context.Execute("var x = {'answer':42, 'tellme':function (x) { return x+' '+this.answer; }}");
                        // Get it and use "dynamic" to tell the compiler to use runtime binding.
                        dynamic x = context.GetVariable("x");
                        // Call the method and print the result. This will print:
                        // "What is the answer to ...? 42"
                        Console.WriteLine(x.tellme("What is the answer to ...?"));
                    }
                    GC.Collect();
                    js.DumpHeapStats();
                }
            }
        }
Exemplo n.º 9
0
        public static void Main(string[] args)
        {
            // string lodash = File.ReadAllText(@"c:\lodash.js");
            using (JsEngine engine = new JsEngine())
            {
                //Stopwatch watch = new Stopwatch();
                //	watch.Start();
                JsScript script = engine.CompileScript("3+3");
                using (JsContext ctx = engine.CreateContext())
                {
                    ctx.Execute(script);
                }
            }

            debugtest dbg = new debugtest();

            //	Delegate.CreateDelegate()
            //Dictionary<string, object> values = new Dictionary<string, object>();

            //values["test"] = 333;
            while (true)
            {
                using (JsEngine js = new JsEngine(4, 32))
                {
                    using (JsContext context = js.CreateContext())
                    {
                        //context.SetVariable("dbg", dbg);
                        //object result = context.Execute("dbg.Write(dbg.valueOf());");
                        context.SetVariableFromAny("Debug", typeof(debugtest));

                        object result = context.Execute("Debug.BoolTest(3,4);");

                    }
                    GC.Collect();
                    js.DumpHeapStats();
                }
            }

            //context.SetVariable("values", values);
            //object result = context.Execute("dbg.runFunc(); values.test ? true : false;");

            //	object result =
            //	context.Execute("var obj = { test: 0 }; obj.ft = function (v) { dbg.Write(v); return 'from JS'; }; dbg.runFunc(obj.ft); dbg.write(obj.test);");

            //int a = 1;

            //	context.SetFunction("runfunc", new Func<int, bool>(Activate));
            //object result = context.Execute("runfunc(2);");
            //  }

            //		}
            //}
            /*using (JsEngine js = new JsEngine()) {
                using (JsContext context = js.CreateContext()) {
                    using (JsScript script = js.CompileScript("3 * 4")) {
                        object result = context.Execute(script, TimeSpan.FromHours(200));
                        Console.WriteLine(result);
                    }
                }
            }*/

            //return;
            /*
            using (JsEngine js = new JsEngine()) {
                using (JsContext context = js.CreateContext()) {
                    for (int i = 0; i < 10; i++) {
                        context.SetVariable("a", new Simple { N = i, S = (i * 10).ToString() });
                        Console.WriteLine(context.Execute("a.N+' '+a.S"));
                    }
                    Console.WriteLine(context.Execute("a.N+' '+a.X"));
                }
            }*/
        }
Exemplo n.º 10
0
 public JsConvert(JsEngine engine)
 {
     _engine = engine;
 }
Exemplo n.º 11
0
Arquivo: Form1.cs Projeto: killf/V8Net
        private void button1_Click(object sender, EventArgs e)
        {
            JsBridge.dbugTestCallbacks();

            JsTypeDefinition jstypedef = new JsTypeDefinition("AA");
            jstypedef.AddMember(new JsMethodDefinition("B", args =>
            {
                args.SetResult(100);
            }));
            jstypedef.AddMember(new JsMethodDefinition("C", args =>
            {
                args.SetResult(true);
            }));
            //===============================================================
            //create js engine and context
            using (JsEngine engine = new JsEngine())
            using (JsContext ctx = engine.CreateContext())
            {

                if (!jstypedef.IsRegisterd)
                {
                    ctx.RegisterTypeDefinition(jstypedef);
                }
                GC.Collect();
                System.Diagnostics.Stopwatch stwatch = new System.Diagnostics.Stopwatch();
                stwatch.Start();

                TestMe1 t1 = new TestMe1();
                var proxy = ctx.CreateWrapper(t1, jstypedef);

                for (int i = 2000; i >= 0; --i)
                {
                    ctx.SetVariableFromAny("x", proxy);
                    object result = ctx.Execute("(function(){if(x.C()){return  x.B();}else{return 0;}})()");
                }
                stwatch.Stop();

                Console.WriteLine("met1 template:" + stwatch.ElapsedMilliseconds.ToString());
                //Assert.That(result, Is.EqualTo(100));
            }
        }
Exemplo n.º 12
0
Arquivo: Form1.cs Projeto: killf/V8Net
        private void button8_Click(object sender, EventArgs e)
        {
            int version = JsBridge.LibVersion;
            JsBridge.dbugTestCallbacks();
            using (JsEngine engine = new JsEngine())
            using (JsContext ctx = engine.CreateContext(new MyJsTypeDefinitionBuilder()))
            {

                GC.Collect();
                System.Diagnostics.Stopwatch stwatch = new System.Diagnostics.Stopwatch();
                stwatch.Reset();
                stwatch.Start();

                var ab = new AboutMe();
                ctx.SetVariableAutoWrap("x", ab);

                string testsrc = @"(function(){
                    x.AttachEvent('mousedown',function(evArgs){});
                    x.FireEventMouseDown({});
                })()";
                object result = ctx.Execute(testsrc);
                stwatch.Stop();

                Console.WriteLine("met1 template:" + stwatch.ElapsedMilliseconds.ToString());

            }
        }
Exemplo n.º 13
0
 public JsConvert(JsEngine engine)
 {
     _engine = engine;
 }
Exemplo n.º 14
0
Arquivo: Form1.cs Projeto: killf/V8Net
        private void button5_Click(object sender, EventArgs e)
        {
            JsBridge.dbugTestCallbacks();
            JsTypeDefinition jstypedef = new JsTypeDefinition("AA");
            jstypedef.AddMember(new JsMethodDefinition("B", args =>
            {
                var argCount = args.ArgCount;
                var thisArg = args.GetThisArg();
                var arg0 = args.GetArgAsObject(0);
                args.SetResult((bool)arg0);

            }));
            jstypedef.AddMember(new JsMethodDefinition("C", args =>
            {
                args.SetResult(true);
            }));

            //-----------------------------------------------------
            jstypedef.AddMember(new JsPropertyDefinition("D",
                args =>
                {
                    var ab = new AboutMe();
                    args.SetResultAutoWrap(ab);
                },
                args =>
                {
                    //setter
                }));
            jstypedef.AddMember(new JsPropertyDefinition("E",
                args =>
                {   //getter
                    args.SetResult(250);
                },
                args =>
                {
                    //setter
                }));
            //===============================================================
            //create js engine and context
            using (JsEngine engine = new JsEngine())
            using (JsContext ctx = engine.CreateContext())
            {

                ctx.RegisterTypeDefinition(jstypedef);

                GC.Collect();
                System.Diagnostics.Stopwatch stwatch = new System.Diagnostics.Stopwatch();
                stwatch.Reset();
                stwatch.Start();

                TestMe1 t1 = new TestMe1();

                INativeScriptable proxy = ctx.CreateWrapper(t1, jstypedef);
                ctx.SetVariable("x", proxy);

                string testsrc = "x.B(x.D.IsOK);";
                object result = ctx.Execute(testsrc);
                stwatch.Stop();

                Console.WriteLine("met1 template:" + stwatch.ElapsedMilliseconds.ToString());

            }
        }
Exemplo n.º 15
0
Arquivo: Form1.cs Projeto: killf/V8Net
        private void button2_Click(object sender, EventArgs e)
        {
            JsBridge.dbugTestCallbacks();

            //create js engine and context

            using (JsEngine engine = new JsEngine())
            using (JsContext ctx = engine.CreateContext())
            {
                GC.Collect();
                System.Diagnostics.Stopwatch stwatch = new System.Diagnostics.Stopwatch();
                stwatch.Start();

                TestMe1 t1 = new TestMe1();

                for (int i = 2000; i >= 0; --i)
                {
                    ctx.SetVariableFromAny("x", t1);
                    object result = ctx.Execute("(function(){if(x.C()){return  x.B();}else{return 0;}})()");
                }
                stwatch.Stop();
                Console.WriteLine("met2 managed reflection:" + stwatch.ElapsedMilliseconds.ToString());
                //Assert.That(result, Is.EqualTo(100));
            }
        }
Exemplo n.º 16
0
Arquivo: Form1.cs Projeto: killf/V8Net
        private void button7_Click(object sender, EventArgs e)
        {
            JsBridge.dbugTestCallbacks();

            using (JsEngine engine = new JsEngine())
            using (JsContext ctx = engine.CreateContext(new MyJsTypeDefinitionBuilder()))
            {

                GC.Collect();
                System.Diagnostics.Stopwatch stwatch = new System.Diagnostics.Stopwatch();
                stwatch.Reset();
                stwatch.Start();

                var ab = new AboutMe();
                ctx.SetVariableAutoWrap("x", ab);

                //string testsrc = "x.IsOK;";
                string testsrc = "x.NewAboutMe();";
                object result = ctx.Execute(testsrc);
                stwatch.Stop();

                Console.WriteLine("met1 template:" + stwatch.ElapsedMilliseconds.ToString());

            }
        }
Exemplo n.º 17
0
        public JsValue ToJsValue(object obj)
        {
            if (obj == null)
            {
                return new JsValue {
                           Type = JsValueType.Null
                }
            }
            ;

            Type type = obj.GetType();

            // Check for nullable types (we will cast the value out of the box later).

            if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable <>))
            {
                type = type.GetGenericArguments()[0];
            }

            if (type == typeof(Boolean))
            {
                return new JsValue {
                           Type = JsValueType.Boolean, I32 = (bool)obj ? 1 : 0
                }
            }
            ;

            if (type == typeof(String) || type == typeof(Char))
            {
                // We need to allocate some memory on the other side; will be free'd by unmanaged code.
                return(JsEngine.jsvalue_alloc_string(obj.ToString()));
            }

            if (type == typeof(Byte))
            {
                return new JsValue {
                           Type = JsValueType.Integer, I32 = (int)(Byte)obj
                }
            }
            ;
            if (type == typeof(Int16))
            {
                return new JsValue {
                           Type = JsValueType.Integer, I32 = (int)(Int16)obj
                }
            }
            ;
            if (type == typeof(UInt16))
            {
                return new JsValue {
                           Type = JsValueType.Integer, I32 = (int)(UInt16)obj
                }
            }
            ;
            if (type == typeof(Int32))
            {
                return new JsValue {
                           Type = JsValueType.Integer, I32 = (int)obj
                }
            }
            ;
            if (type == typeof(UInt32))
            {
                return new JsValue {
                           Type = JsValueType.Integer, I32 = (int)(UInt32)obj
                }
            }
            ;

            if (type == typeof(Int64))
            {
                return new JsValue {
                           Type = JsValueType.Number, Num = (double)(Int64)obj
                }
            }
            ;
            if (type == typeof(UInt64))
            {
                return new JsValue {
                           Type = JsValueType.Number, Num = (double)(UInt64)obj
                }
            }
            ;
            if (type == typeof(Single))
            {
                return new JsValue {
                           Type = JsValueType.Number, Num = (double)(Single)obj
                }
            }
            ;
            if (type == typeof(Double))
            {
                return new JsValue {
                           Type = JsValueType.Number, Num = (double)obj
                }
            }
            ;
            if (type == typeof(Decimal))
            {
                return new JsValue {
                           Type = JsValueType.Number, Num = (double)(Decimal)obj
                }
            }
            ;

            if (type == typeof(DateTime))
            {
                return new JsValue {
                           Type = JsValueType.Date,
                           Num  = (((DateTime)obj).Ticks - 621355968000000000.0 + 26748000000000.0) / 10000.0
                }
            }
            ;

            // Arrays of anything that can be cast to object[] are recursively convertef after
            // allocating an appropriate jsvalue on the unmanaged side.

            var array = obj as object[];

            if (array != null)
            {
                JsValue v = JsEngine.jsvalue_alloc_array(array.Length);

                if (v.Length != array.Length)
                {
                    throw new JsInteropException("can't allocate memory on the unmanaged side");
                }
                for (int i = 0; i < array.Length; i++)
                {
                    Marshal.StructureToPtr(ToJsValue(array[i]), (v.Ptr + 16 * i), false);
                }
                return(v);
            }

            // Every object explicitly converted to a value becomes an entry of the
            // _keepalives list, to make sure the GC won't collect it while still in
            // use by the unmanaged Javascript engine. We don't try to track duplicates
            // because adding the same object more than one time acts more or less as
            // reference counting.

            return(new JsValue {
                Type = JsValueType.Managed, Index = _engine.KeepAliveAdd(obj)
            });
        }
    }
}