Пример #1
0
 JavaScriptValue ObjectToJavaScriptValue(Object parameter)
 {
     if (parameter == null)
     {
         return(JavaScriptValue.Null);
     }
     else if (parameter is String)
     {
         return(JavaScriptValue.FromString(parameter.ToString()));
     }
     else if (parameter is Boolean)
     {
         return(JavaScriptValue.FromBoolean((Boolean)parameter));
     }
     else if (parameter is Int32)
     {
         return(JavaScriptValue.FromInt32((Int32)parameter));
     }
     else if (parameter is Double)
     {
         return(JavaScriptValue.FromDouble((Int32)parameter));
     }
     else if (parameter is Object)
     {
         String json  = JsonConvert.SerializeObject(parameter);
         var    glob  = JavaScriptValue.GlobalObject.GetProperty(JavaScriptPropertyId.FromString("JSON"));
         var    parse = glob.GetProperty(JavaScriptPropertyId.FromString("parse"));
         return(parse.CallFunction(JavaScriptValue.Undefined, JavaScriptValue.FromString(json)));
     }
     return(JavaScriptValue.Undefined);
 }
Пример #2
0
        public static JavaScriptModuleRecord Create(JavaScriptModuleRecord?parent, string name)
        {
            JavaScriptValue moduleName;

            if (string.IsNullOrEmpty(name))
            {
                moduleName = JavaScriptValue.Invalid;
            }
            else
            {
                moduleName = JavaScriptValue.FromString(name);
            }
            JavaScriptModuleRecord result;

            if (parent.HasValue)
            {
                Native.ThrowIfError(Native.JsInitializeModuleRecord(parent.Value, moduleName, out result));
            }
            else
            {
                Native.ThrowIfError(Native.JsInitializeModuleRecord(NULLModuleRecord, moduleName, out result));
            }

            return(result);
        }
        private JavaScriptValue NativeCallSyncHook(
            JavaScriptValue callee,
            bool isConstructCall,
            JavaScriptValue[] arguments,
            ushort argumentCount,
            IntPtr callbackData)
        {
            if (argumentCount != 4)
            {
                throw new ArgumentOutOfRangeException(nameof(argumentCount), "Expected exactly four arguments (global, moduleId, methodId, and args).");
            }

            if (_callSyncHook == null)
            {
                throw new InvalidOperationException("Sync hook has not been set.");
            }

            var moduleId = (int)arguments[1].ToDouble();
            var methodId = (int)arguments[2].ToDouble();
            var args     = (JArray)ConvertJson(arguments[3]);

            try
            {
                var result = _callSyncHook(moduleId, methodId, args);
                return(ConvertJson(result));
            }
            catch (Exception e)
            {
                var error = JavaScriptValue.CreateError(JavaScriptValue.FromString(e.Message));
                Native.JsSetException(error);
                return(JavaScriptValue.Invalid);
            }
        }
Пример #4
0
        public static void Register(JavaScriptContext context)
        {
            var global = JavaScriptValue.GlobalObject;

            global.SetProperty("global", global);
            global.SetProperty("window", global);

            global.SetProperty(
                "atob",
                Bridge.CreateFunction("atob", (args) => {
                return(JavaScriptValue.FromString(
                           System.Text.Encoding.UTF8.GetString(System.Convert.FromBase64String(args[1].ToString()))
                           ));
            })
                );

            global.SetProperty(
                "btoa",
                Bridge.CreateFunction("btoa", (args) => {
                return(JavaScriptValue.FromString(
                           System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(args[1].ToString()))
                           ));
            })
                );
        }
Пример #5
0
        private static JavaScriptValue Format(JavaScriptValue callee, bool isConstructCall, JavaScriptValue[] arguments, ushort argumentCount, IntPtr callbackData)
        {
            JavaScriptValue obj      = arguments[1];
            string          pathName = JSValToString(obj.GetProperty(JavaScriptPropertyId.FromString("pathname"))).Replace("\\", "/");
            string          protocol = JSValToString(obj.GetProperty(JavaScriptPropertyId.FromString("protocol")));

            return(JavaScriptValue.FromString(protocol + "//" + pathName));
        }
Пример #6
0
        private static void ThrowException(string errorString)
        {
            // We ignore error since we're already in an error state.
            JavaScriptValue errorValue  = JavaScriptValue.FromString(errorString);
            JavaScriptValue errorObject = JavaScriptValue.CreateError(errorValue);

            JavaScriptContext.SetException(errorObject);
        }
Пример #7
0
 static JavaScriptValue TestJSNativeFunction2(JavaScriptValue callee,
                                              [MarshalAs(UnmanagedType.U1)] bool isConstructCall,
                                              [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] JavaScriptValue[] arguments,
                                              ushort argumentCount,
                                              IntPtr callbackData)
 {
     JavaScriptContext.SetException(JavaScriptValue.CreateError(JavaScriptValue.FromString("test error")));
     return(JavaScriptValue.Invalid);
 }
Пример #8
0
        static public JavaScriptValue SetJSException(Exception e)
        {
            var v = JavaScriptValue.CreateExternalObject(GCHandle.ToIntPtr(GCHandle.Alloc(e)), FreeDg);

            v.AddRef();
            v.SetIndexedProperty(JavaScriptValue.FromString("toString"), JavaScriptValue.FromString(e.ToString()));
            Native.JsSetException(JavaScriptValue.CreateError(v));
            return(JavaScriptValue.Invalid);
        }
        private JavaScriptValue ConvertJson(JToken token)
        {
            var parseFunction = EnsureParseFunction();

            var json      = token.ToString(Formatting.None);
            var jsonValue = JavaScriptValue.FromString(json);

            return(parseFunction.CallFunction(_globalObject, jsonValue));
        }
Пример #10
0
 private static JavaScriptValue Join(JavaScriptValue callee, bool isConstructCall, JavaScriptValue[] arguments, ushort argumentCount, IntPtr callbackData)
 {
     string[] args = new string[arguments.Length - 1];
     for (int i = 1; i < arguments.Length; i++)
     {
         args[i - 1] = JSValToString(arguments[i]);
     }
     return(JavaScriptValue.FromString(String.Join("\\", args)));
 }
        /// <summary>
        /// Call the JavaScript method from the given module.
        /// </summary>
        /// <param name="moduleName">The module name.</param>
        /// <param name="methodName">The method name.</param>
        /// <param name="arguments">The arguments.</param>
        /// <returns>The result of the call.</returns>
        public JToken Call(string moduleName, string methodName, JArray arguments)
        {
            if (moduleName == null)
            {
                throw new ArgumentNullException(nameof(moduleName));
            }
            if (methodName == null)
            {
                throw new ArgumentNullException(nameof(methodName));
            }
            if (arguments == null)
            {
                throw new ArgumentNullException(nameof(arguments));
            }

            // Try get global property
            var globalObject     = EnsureGlobalObject();
            var modulePropertyId = JavaScriptPropertyId.FromString(moduleName);
            var module           = globalObject.GetProperty(modulePropertyId);

            if (module.ValueType != JavaScriptValueType.Object)
            {
                var requireFunction = EnsureRequireFunction();

                // Get the module
                var moduleString     = JavaScriptValue.FromString(moduleName);
                var requireArguments = new[] { globalObject, moduleString };
                module = requireFunction.CallFunction(requireArguments);
            }

            // Get the method
            var methodPropertyId = JavaScriptPropertyId.FromString(methodName);
            var method           = module.GetProperty(methodPropertyId);

            // Set up the arguments to pass in
            var callArguments = new JavaScriptValue[arguments.Count + 1];

            callArguments[0] = EnsureGlobalObject(); // TODO: What is first argument?

            for (var i = 0; i < arguments.Count; ++i)
            {
                var converted = ConvertJson(arguments[i]);
                converted.AddRef();
                callArguments[i + 1] = converted;
            }

            // Invoke the function
            var result = method.CallFunction(callArguments);

            for (var i = 1; i < callArguments.Length; ++i)
            {
                callArguments[i].Release();
            }

            // Convert the result
            return(ConvertJson(result));
        }
Пример #12
0
 public void ExecuteModule(string entryPointModuleIdentifier)
 {
     using (new JavaScriptContext.Scope(context))
     {
         var sourceCode      = resourceLoader.Load(new Uri("resm:RaisingStudio.NativeScript.require.js"));
         var requireFunction = this.Execute(sourceCode, "require.js");
         var require         = requireFunction.CallFunction(JavaScriptValue.FromString(this.applicationPath), JavaScriptValue.CreateFunction(createModuleDelegate));
         require.CallFunction(JavaScriptValue.FromString(entryPointModuleIdentifier));
     }
 }
Пример #13
0
        public static void Register(JavaScriptContext context)
        {
            updateCallbacks.Clear();
            oneUpdateCallbacks.Clear();

            JavaScriptValue UpdateHelper = JavaScriptValue.CreateObject();

            JavaScriptValue.GlobalObject.SetProperty(
                "UpdateHelper",
                UpdateHelper
                );

            UpdateHelper.SetProperty(
                "addUpdateHook",
                Bridge.CreateFunction(
                    "addUpdateHook",
                    (args) => {
                return(JavaScriptValue.FromString(
                           addUpdateHook(args[1])
                           ));
            }
                    )
                );

            UpdateHelper.SetProperty(
                "removeUpdateHook",
                Bridge.CreateFunction(
                    "removeUpdateHook",
                    (args) => {
                removeUpdateHook(args[1].ToString());
            }
                    )
                );

            UpdateHelper.SetProperty(
                "removeAllUpdateHooks",
                Bridge.CreateFunction(
                    "removeAllUpdateHooks",
                    (args) => {
                updateCallbacks.Clear();
                oneUpdateCallbacks.Clear();
            }
                    )
                );

            UpdateHelper.SetProperty(
                "addOneUpdateHook",
                Bridge.CreateFunction(
                    "addOneUpdateHook",
                    (args) => {
                addOneUpdateHook(args[1]);
            }
                    )
                );
        }
        private void button4_Click(object sender, EventArgs e)
        {
            JavaScriptRuntime       runtime;
            JavaScriptContext       context;
            JavaScriptSourceContext currentSourceContext = JavaScriptSourceContext.FromIntPtr(IntPtr.Zero);

            JavaScriptValue      DbgStringFn;
            JavaScriptValue      DbgStringName;
            JavaScriptPropertyId DbgStringId;
            JavaScriptValue      SumFn;
            JavaScriptValue      SumName;
            JavaScriptPropertyId SumId;

            IntPtr callbackState = IntPtr.Zero;

            bool bSuccess = false;

            try
            {
                string script = System.IO.File.ReadAllText("C:/Temp/Script/Sample04.js");


                runtime = JavaScriptRuntime.Create();
                context = runtime.CreateContext();
                JavaScriptContext.Current = context;


                DbgStringName = JavaScriptValue.FromString("DbgString");
                DbgStringId   = JavaScriptPropertyId.FromString("DbgString");
                Native.JsCreateNamedFunction(DbgStringName, (ChakraHost.Hosting.JavaScriptNativeFunction)DbgString, callbackState, out DbgStringFn);
                JavaScriptValue.GlobalObject.SetProperty(DbgStringId, DbgStringFn, true);


                SumName = JavaScriptValue.FromString("Sum");
                SumId   = JavaScriptPropertyId.FromString("Sum");
                Native.JsCreateNamedFunction(SumName, (ChakraHost.Hosting.JavaScriptNativeFunction)Sum, callbackState, out SumFn);
                JavaScriptValue.GlobalObject.SetProperty(SumId, SumFn, true);

                JavaScriptContext.RunScript(script, currentSourceContext++, "");

                bSuccess = true;
            }
            finally
            {
                if (true == bSuccess)
                {
                    System.Diagnostics.Trace.WriteLine("Success");
                }
                else
                {
                    System.Diagnostics.Trace.WriteLine("Error");
                }
            }
        }
Пример #15
0
        private static async Task <JavaScriptValue> DoSuccessfulWork(
            JavaScriptValue callee,
            bool isConstructCall,
            JavaScriptValue[] arguments,
            ushort argumentCount,
            IntPtr callbackData)
        {
            await Task.Delay(200);

            return(JavaScriptValue.FromString("promise from native code"));
        }
        private JavaScriptValue ConvertJson(string jsonString)
        {
            var jsonStringValue = JavaScriptValue.FromString(jsonString);

            jsonStringValue.AddRef();
            var parseFunction = EnsureParseFunction();
            var jsonValue     = parseFunction.CallFunction(_globalObject, jsonStringValue);

            jsonStringValue.Release();
            return(jsonValue);
        }
Пример #17
0
        public static JavaScriptValue ToBase64(JavaScriptValue callee, bool isconstructcall, JavaScriptValue[] arguments, ushort argumentcount, IntPtr callbackdata)
        {
            if (argumentcount < 2)
            {
                return(JavaScriptValue.FromString(""));
            }

            var stringToEncode = arguments[1].ToString();

            return(JavaScriptValue.FromString(Convert.ToBase64String(Encoding.UTF8.GetBytes(stringToEncode))));
        }
        private JavaScriptValue JSGetPushClients(JavaScriptValue callee, bool isConstructCall, JavaScriptValue[] arguments, ushort argumentCount, IntPtr callbackData)
        {
            List <string>   clientIds = new List <string>(this.WebSocketClients.GetAll().Keys);
            JavaScriptValue outValue  = JavaScriptValue.CreateArray((uint)clientIds.Count);

            for (int i = 0; i < clientIds.Count; i++)
            {
                outValue.SetIndexedProperty(JavaScriptValue.FromInt32(i), JavaScriptValue.FromString(clientIds[i]));
            }

            return(outValue);
        }
        public static JavaScriptValue JsConstructor(JavaScriptValue callee, bool isConstructCall, JavaScriptValue[] arguments, ushort argumentCount, IntPtr callbackData)
        {
            if (!isConstructCall)
            {
                return(JavaScriptValue.Invalid);
            }

            IntPtr objId;

            do
            {
                objId = new IntPtr(new Random().Next());
            } while(instances.ContainsKey(objId));
            var jsObj     = JavaScriptValue.CreateExternalObject(objId, null);
            var actualObj = new JsXmlHttpRequest(jsObj);

            instances.Add(objId, actualObj);

            // Properties
            jsObj.SetProperty(JavaScriptPropertyId.FromString("readyState"), JavaScriptValue.FromInt32((int)ReadyStates.Unsent), true);
            jsObj.SetProperty(JavaScriptPropertyId.FromString("response"), JavaScriptValue.FromString(""), true);
            jsObj.SetProperty(JavaScriptPropertyId.FromString("responseText"), JavaScriptValue.FromString(""), true);
            jsObj.SetProperty(JavaScriptPropertyId.FromString("responseType"), JavaScriptValue.FromString(""), true);
            jsObj.SetProperty(JavaScriptPropertyId.FromString("responseUrl"), JavaScriptValue.FromString(""), true);
            //jsObj.SetProperty(JavaScriptPropertyId.FromString("responseXML"), JavaScriptValue.Null, true);
            jsObj.SetProperty(JavaScriptPropertyId.FromString("status"), JavaScriptValue.FromInt32(0), true);
            jsObj.SetProperty(JavaScriptPropertyId.FromString("statusText"), JavaScriptValue.FromString(""), true);
            //jsObj.SetProperty(JavaScriptPropertyId.FromString("timeout"), JavaScriptValue.FromInt32(0), true);
            //jsObj.SetProperty(JavaScriptPropertyId.FromString("upload"), JavaScriptValue.Null, true);
            //jsObj.SetProperty(JavaScriptPropertyId.FromString("withCredentials"), JavaScriptValue.FromBoolean(false), true);

            // Event properties
            //jsObj.SetProperty(JavaScriptPropertyId.FromString("onabort"), JavaScriptValue.Null, true);
            jsObj.SetProperty(JavaScriptPropertyId.FromString("onerror"), JavaScriptValue.Null, true);
            jsObj.SetProperty(JavaScriptPropertyId.FromString("onload"), JavaScriptValue.Null, true);
            //jsObj.SetProperty(JavaScriptPropertyId.FromString("onloadstart"), JavaScriptValue.Null, true);
            //jsObj.SetProperty(JavaScriptPropertyId.FromString("onprogress"), JavaScriptValue.Null, true);
            //jsObj.SetProperty(JavaScriptPropertyId.FromString("ontimeout"), JavaScriptValue.Null, true);
            //jsObj.SetProperty(JavaScriptPropertyId.FromString("onloadend"), JavaScriptValue.Null, true);
            jsObj.SetProperty(JavaScriptPropertyId.FromString("onreadystatechange"), JavaScriptValue.Null, true);
            //jsObj.SetProperty(JavaScriptPropertyId.FromString("ontimeout"), JavaScriptValue.Null, true);

            // Methods
            //jsObj.SetProperty(JavaScriptPropertyId.FromString("abort"), JavaScriptValue.CreateFunction(functions["abort"]), true);
            //jsObj.SetProperty(JavaScriptPropertyId.FromString("getAllResponseHeaders"), JavaScriptValue.CreateFunction(functions["getAllResponseHeaders"]), true);
            jsObj.SetProperty(JavaScriptPropertyId.FromString("open"), JavaScriptValue.CreateFunction(functions["open"]), true);
            //jsObj.SetProperty(JavaScriptPropertyId.FromString("overrideMimeType"), JavaScriptValue.CreateFunction(functions["overrideMimeType"]), true);
            jsObj.SetProperty(JavaScriptPropertyId.FromString("send"), JavaScriptValue.CreateFunction(functions["send"]), true);
            jsObj.SetProperty(JavaScriptPropertyId.FromString("setRequestHeader"), JavaScriptValue.CreateFunction(functions["setRequestHeader"]), true);

            return(jsObj);
        }
Пример #20
0
 public static JavaScriptValue ParseScript(
     string script,
     string sourceName      = "ParseScript",
     bool ignoreScriptError = false
     )
 {
     return(ParseScript(
                JavaScriptValue.FromString(script),
                JavaScriptSourceContext.None,
                JavaScriptValue.FromString(sourceName),
                JavaScriptParseScriptAttributes.JsParseScriptAttributeNone,
                ignoreScriptError
                ));
 }
Пример #21
0
 public static JavaScriptModuleRecord Initialize(
     JavaScriptModuleRecord?referencingModule,
     string normalizedSpecifier
     )
 {
     if (string.IsNullOrEmpty(normalizedSpecifier))
     {
         return(Initialize(referencingModule));
     }
     else
     {
         return(Initialize(referencingModule, JavaScriptValue.FromString(normalizedSpecifier)));
     }
 }
Пример #22
0
 internal static JavaScriptValue GetSavedString(JavaScriptValue callee,
                                                [MarshalAs(UnmanagedType.U1)] bool isConstructCall,
                                                [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] JavaScriptValue[] arguments,
                                                ushort argumentCount,
                                                IntPtr callbackData)
 {
     try
     {
         return(JavaScriptValue.FromString((string)GCHandle.FromIntPtr(callbackData).Target));
     }
     catch (Exception e)
     {
         return(ExceptionUtil.SetJSException(e));
     }
 }
Пример #23
0
        private static void WireUp(JavaScriptValue constructor, System.Type type, JavaScriptValue prototype)
        {
            string name = type.ToString();

            typeNameToType[name] = type;

            // So that we can look up c# types by JS constructors, define a name property containing
            // the full name from type.ToString() that we can take off and put back into stringToType.
            JavaScriptValue propertyDescriptor = JavaScriptValue.CreateObject();

            propertyDescriptor.SetProperty("value", JavaScriptValue.FromString(name));
            constructor.DefineProperty("name", propertyDescriptor);

            typeNameToPrototype[name] = prototype;
        }
Пример #24
0
        private Tuple <ChakraContext, JSValue> CreateChakraContext()
        {
            JavaScriptHosting       hosting = JavaScriptHosting.Default; //get default host instantce
            JavaScriptHostingConfig config  = new JavaScriptHostingConfig();

            config.AddModuleFolder("wwwroot/dist/js"); //set script folder

            var chakraContext = hosting.CreateContext(config);

            // Function Converter
            var valueServices = chakraContext.ServiceNode.GetService <IJSValueConverterService>();

            valueServices.RegisterFunctionConverter <string>();
            valueServices.RegisterProxyConverter <EvConsole>((binding, instance, serviceNode) =>
            {
                binding.SetMethod <string>("log", instance.Log);
            });

            // EvContext Converter
            valueServices.RegisterStructConverter <EvContext>((to, from) => { to.WriteProperty("title", from.Title); },
                                                              (from) => new EvContext
            {
                Title = from.ReadProperty <string>("title")
            });

            var console = new EvConsole();

            chakraContext.GlobalObject.WriteProperty("console", console);

            chakraContext.Enter();
            // https://ssr.vuejs.org/guide/non-node.html
            var obj = JavaScriptValue.CreateObject();

            obj.SetProperty(JavaScriptPropertyId.FromString("VUE_ENV"), JavaScriptValue.FromString("server"), false);
            obj.SetProperty(JavaScriptPropertyId.FromString("NODE_ENV"), JavaScriptValue.FromString("production"),
                            false);

            var process = JavaScriptValue.CreateObject();

            process.SetProperty(JavaScriptPropertyId.FromString("env"), obj, false);

            chakraContext.GlobalObject.WriteProperty(JavaScriptPropertyId.FromString("process"), process);
            chakraContext.Leave();

            var appClass = chakraContext.ProjectModuleClass("entrypoint", "App", config.LoadModule);

            return(Tuple.Create(chakraContext, appClass));
        }
Пример #25
0
        public static JavaScriptValue ToJavaScriptValue(this object it)
        {
            switch (it)
            {
            case JavaScriptValue javaScriptValue:
                return(javaScriptValue);

            case bool value:
                return(JavaScriptValue.FromBoolean(value));

            case string value:
                return(JavaScriptValue.FromString(value));

            case int value:
                return(JavaScriptValue.FromInt32(value));

            case double value:
                return(JavaScriptValue.FromDouble(value));

            case float value:
                return(JavaScriptValue.FromDouble(value));

            case decimal value:
                return(JavaScriptValue.FromDouble(Convert.ToDouble(value)));

            case null:
                return(JavaScriptValue.Null);

            default:
                ITypeConversion converter = null;
                var             type      = it.GetType();
                foreach (var item in Conversions)
                {
                    if (item.ObjectType == type)
                    {
                        converter = item;
                        break;
                    }

                    if (item.ObjectType.IsAssignableFrom(type))
                    {
                        converter = item;
                    }
                }

                return(converter?.ToJsValue?.Invoke(it) ?? JavaScriptValue.Invalid);
            }
        }
Пример #26
0
 JavaScriptValue ObjectToJavaScriptValue(Object parameter)
 {
     if (parameter == null)
     {
         return(JavaScriptValue.Null);
     }
     else if (parameter is String)
     {
         return(JavaScriptValue.FromString(parameter.ToString()));
     }
     else if (parameter is Boolean)
     {
         return(JavaScriptValue.FromBoolean((Boolean)parameter));
     }
     return(JavaScriptValue.Undefined);
 }
Пример #27
0
 public static JavaScriptValue ParseScript(
     string script,
     JavaScriptSourceContext sourceContext,
     string sourceName,
     JavaScriptParseScriptAttributes parseAttributes,
     bool ignoreScriptError = false
     )
 {
     return(ParseScript(
                JavaScriptValue.FromString(script),
                sourceContext,
                JavaScriptValue.FromString(sourceName),
                parseAttributes,
                ignoreScriptError
                ));
 }
Пример #28
0
 static JavaScriptValue body(JavaScriptValue callee,
                             [MarshalAs(UnmanagedType.U1)] bool isConstructCall,
                             [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] JavaScriptValue[] arguments,
                             ushort argumentCount,
                             IntPtr callbackData)
 {
     try
     {
         var that        = (OverloadSelector)GCHandle.FromIntPtr(callbackData).Target;
         var lastIdx     = -1;
         var lowestScore = OverloadEntry.DENIED - 1; // block denied
         for (int i = 0; i < that.methodInfos.Count; i++)
         {
             var mi    = that.methodInfos[i];
             var score = mi.GetArgumentsScore(arguments);
             if (lowestScore > score)
             {
                 lowestScore = score;
                 lastIdx     = i;
             }
             else if (lowestScore == score)
             {
                 lastIdx = -1; // deny ambiguous overload
             }
         }
         if (lastIdx == -1)
         {
             Native.JsSetException(JavaScriptValue.CreateError(JavaScriptValue.FromString("ambiguous overload " + that.GetName())));
             return(JavaScriptValue.Invalid);
         }
         var method = that.methodInfos[lastIdx];
         if (method.cachedFunction == null)
         {
             method.cachedFunction = method.entityWrapper.Wrap();
         }
         if (!method.cachedData.IsAllocated)
         {
             method.cachedData = GCHandle.Alloc(method.entityWrapper);
         }
         return(method.cachedFunction(callee, isConstructCall, arguments, argumentCount, GCHandle.ToIntPtr(method.cachedData)));
     }
     catch (Exception e)
     {
         return(ExceptionUtil.SetJSException(e));
     }
 }
Пример #29
0
        void AssignMethodProc(JavaScriptValue setTo, MethodInfo[] methods)
        {
            var methodDic = new Dictionary <string, List <MethodInfo> >();

            foreach (var m in methods)
            {
                if (m.IsSpecialName)
                {
                    continue;
                }
                if (m.IsGenericMethodDefinition)
                {
                    continue;
                }
                if (m.IsGenericMethod)
                {
                    continue;
                }
                if (!methodDic.ContainsKey(m.Name))
                {
                    methodDic[m.Name] = new List <MethodInfo>();
                }
                methodDic[m.Name].Add(m);
            }
            foreach (var methodName in methodDic.Keys)
            {
                var ms = methodDic[methodName];
                if (ms.Count == 1)
                {
                    var m   = ms[0];
                    var smw = (m.IsStatic) ? (FunctionWrapper)StaticMethodWrapper.Wrap(m) : (FunctionWrapper)InstanceMethodWrapper.Wrap(m);
                    setTo.SetIndexedProperty(JavaScriptValue.FromString(m.Name), smw.GetJavaScriptValue());
                    methodWrappers.Add(smw);
                }
                else
                {
                    var os = new OverloadSelector();
                    foreach (var m in ms)
                    {
                        os.AppendMethod(m);
                    }
                    setTo.SetIndexedProperty(JavaScriptValue.FromString(os.GetName()), os.GetJavaScriptValue());
                    methodWrappers.Add(os);
                }
            }
        }
Пример #30
0
        public JSValue Evaluate(string js, string sourceName)
        {
            JavaScriptValue result;
            var             err = Native.JsRun(JavaScriptValue.FromString(js), currentSourceContext++, JavaScriptValue.FromString(sourceName), JavaScriptParseScriptAttributes.JsParseScriptAttributeNone, out result);

            if (err == JavaScriptErrorCode.ScriptException ||
                err == JavaScriptErrorCode.ScriptCompile ||
                err == JavaScriptErrorCode.InExceptionState)
            {
                ThrowError(err, sourceName);
                //throw new ChakraSharpException(ErrorToString(err, sourceName));
            }
            else
            {
                Native.ThrowIfError(err);
            }
            return(JSValue.Make(result));
        }