public ClrCtor(Engine engine, DomConverter converter, Type type) : base(engine, null, null, false) { _type = type; _converter = converter; Prototype = engine.Function.PrototypeObject; FastAddProperty("prototype", _converter.GetPrototype(type), false, false, false); DomConverter.DefineStatic(this, type); }
public ObjectInstance Construct(JsValue[] arguments) { var argsValues = arguments.Select(x => x.ToObject()).ToArray(); var argTypes = argsValues.Select(x => x?.GetType()).ToArray(); if (argTypes.All(x => x != null)) { //todo: why we here do not onvert args? var exactCtor = _type.GetConstructor(argTypes); if (exactCtor != null) { var obj = exactCtor.Invoke(argsValues); JsValue val; if (_converter.TryConvert(obj, out val)) { return(val.AsObject() as ClrObject); } } } foreach (var ctor in _type.GetConstructors()) { var ctorParameters = ctor.GetParameters(); if (ctorParameters.Length == argTypes.Length) { var notMatch = false; for (var i = 0; i < ctorParameters.Length && !notMatch; i++) { if (!DomConverter.Convertible(argTypes[i], ctorParameters[i].ParameterType)) { notMatch = true; } } if (!notMatch) { var args = ConvertArgs(argsValues, ctorParameters.Select(x => x.ParameterType)) .ToArray(); var obj = ctor.Invoke(args); return(new ClrObject(Engine, obj, _converter.GetPrototype(obj.GetType()), _converter)); } } } throw new Exception("Unable to find proper constructor for the type: " + _type.Name); }
public void AddGlobalType(string jsTypeName, object owner, MethodInfo ctorMethod) { var type = ctorMethod.ReturnType; var jsCtor = new ClrFuncCtor(type, _engine, args => { //todo: create executor from methodInfo var clrArgs = ctorMethod.GetParameters().Select((parameterInfo, i) => i < args.Length && args[i].CanConvert(parameterInfo.ParameterType) ? _typeConverter.ConvertToObject(args[i], parameterInfo.ParameterType) : parameterInfo.HasDefaultValue ? parameterInfo.DefaultValue : parameterInfo.ParameterType.IsValueType ? Activator.CreateInstance(parameterInfo.ParameterType) : null).ToArray(); var obj = ctorMethod.Invoke(owner, clrArgs); _typeConverter.TryConvert(obj, out var res); return(res.AsObject()); }, _typeConverter.GetPrototype(type)); _engine.Global.FastAddProperty(jsTypeName, jsCtor, false, false, false); }