/// <summary> /// Gets the results of an IronPython file after execution. /// </summary> /// <typeparam name="EngineResults">Generic result from IronPython class.</typeparam> /// <param name="className">The name of the class to reference.</param> /// <param name="methodName">The name of the method to execute.</param> /// <returns>The results of IronPython execution.</returns> public EngineResults Execute <EngineResults>(string className, string methodName) { source.Execute(scope); var classObj = scope.GetVariable(className); var classInstance = operations.Call(classObj); var classMethod = operations.GetMember(classInstance, methodName); var results = (EngineResults)operations.Call(classMethod); return(results); }
internal PythonProcessor(ObjectOperations op, object processorClass) { var processor = (object)op.CreateInstance(processorClass); Process = op.GetMember <Func <TSource, TResult> >(processor, PythonHelper.ProcessFunction); if (op.ContainsMember(processor, PythonHelper.UnloadFunction)) { Unload = op.GetMember <Action>(processor, PythonHelper.UnloadFunction); } if (op.ContainsMember(processor, PythonHelper.LoadFunction)) { Load = op.GetMember <Action>(processor, PythonHelper.LoadFunction); } }
// get an object's instance variable names ArrayList getInstanceVars(object instance) { ArrayList instanceVars = new ArrayList(); foreach (var name in operations.GetMemberNames(instance)) { object member = operations.GetMember(instance, name); if (!operations.IsCallable(member) && !(name == "__doc__" || name == "__module__" || name == "_object")) // found an instance variable! { instanceVars.Add(name); } } return(instanceVars); }
// Runs my_class's my_method in my_script. // Caller is responsible for casting the returned object. static public object RunPythonMethod(string my_script, string my_class, string my_method) { ScriptEngine engine = Python.CreateEngine(); ScriptScope scope = engine.CreateScope(); ScriptSource source = engine.CreateScriptSourceFromFile(my_script); ObjectOperations op = engine.Operations; var paths = engine.GetSearchPaths(); string path = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location); paths.Add(path); var dir = Path.GetDirectoryName(my_script); paths.Add(dir); engine.SetSearchPaths(paths); source.Execute(scope); object classObject = scope.GetVariable(my_class); object instance = op.Invoke(classObject); object method = op.GetMember(instance, my_method); return(op.Invoke(method)); }
public static TReturn CallMethod <TReturn>(string variableName, string methodName, params object[] args) { try { ObjectOperations ops = _engine.Operations; if (_scope.ContainsVariable(variableName)) { object instance = _scope.GetVariable(variableName); if (instance != null) { if (ops.ContainsMember(instance, methodName)) { object method = ops.GetMember(instance, methodName); return((TReturn)ops.Call(method, args)); } } } return(default(TReturn)); } catch (Exception ex) { #if DEBUG throw ex; #else Log.Write(LogType.Error, ex.ToString()); return(default(TReturn)); #endif } }
public dynamic CallFunction(string method, params dynamic[] arguments) { try { ObjectOperations ops = this.mScriptEngine.Operations; if (this.mScriptClass != null) { if (ops.ContainsMember(this.mScriptClass, method)) { object instance = ops.GetMember(this.mScriptClass, method); if (instance != null) { return(ops.InvokeMember(this.mScriptClass, method, arguments)); } } else { this.mLogger.Error("Missing member when trying to execute method '{0}'.", method); this.mScriptLogger.Error("Missing member when trying to execute method '{0}'.", method); } } return(null); } catch (Exception er) { this.mLogger.Error(er, "Script exception in method '{0}'.", method); this.mScriptLogger.Error(er, "Script exception in method '{0}'.", method); throw er; } }
/// <summary> /// Calls the method. /// </summary> /// <param name="name">Name.</param> public void InvokeMethod(object nameClass, string Method, params object[] parameters) { object output = new object(); if (Operation.TryGetMember(nameClass, Method, out output)) { object Func = Operation.GetMember(nameClass, Method); Operation.Invoke(Func, parameters); } }
internal static Type GetOutputType(ObjectOperations op, object pythonClass, string methodName) { object returnType; var function = (PythonFunction)op.GetMember <Method>(pythonClass, methodName).__func__; if (function.func_dict.TryGetValue(PythonHelper.ReturnTypeAttribute, out returnType)) { return((Type)returnType); } return(typeof(object)); }
bool checkLevel3Cond() { // check if user made the cube spin object cube = scope.GetVariable("c2"); string spinning = operations.GetMember(cube, "spinning").ToString(); if (spinning == "True") { return(true); } return(false); }
/// <summary> /// Remove unuseful delimeters in Equation /// </summary> /// <param name="rawEqation"></param> /// <returns></returns> public static string removingDelimeterOfEq(string rawEqation) { string resultEquation = ""; string getAppPath = System.IO.Directory.GetCurrentDirectory(); int index1; index1 = getAppPath.IndexOf("ExtractEquationFrHwp"); int pathLength = getAppPath.Length; string Lpath; if (index1 > 0) { Lpath = getAppPath.Remove(index1, pathLength - index1); } else { Lpath = getAppPath; } string filePath = Lpath + "ExtractEquationFrHwp\\Delimeters4Equation.py"; ScriptEngine engine = Python.CreateEngine(); ScriptSource source = engine.CreateScriptSourceFromFile(filePath); ScriptScope scope = engine.CreateScope(); ObjectOperations op = engine.Operations; source.Execute(scope); // class object created object classObject = scope.GetVariable("Delimiters4Equation"); // get the class object object instance = op.Invoke(classObject); // create the instance object method = op.GetMember(instance, "getDelimeters"); // get a method List <string> result = ((IList <object>)op.Invoke(method)).Cast <string>().ToList(); string tempText = rawEqation; for (int i = 0; i < result.Count; i++) { tempText = tempText.Replace(result[i], ""); //MessageBox.Show(tempText); } resultEquation = tempText; return(resultEquation); }
public static void Call(string className, string methodName, params object[] args) { ObjectOperations ops = _engine.Operations; if (_scope.ContainsVariable(className)) { object @class = _scope.GetVariable(className); object instance = ops.Call(@class); if (instance != null) { if (ops.ContainsMember(instance, methodName)) { object method = ops.GetMember(instance, methodName); ops.Call(method, args); } } } }
public static object GetMember(this ObjectOperations operations, object instance, string name, Type type) { var rubyTypedValue = operations.GetMember(instance, name); if (type.IsArray) { var untypedArray = (from item in (IEnumerable <dynamic>) rubyTypedValue select operations.ConvertTo(item, type.GetElementType())).ToArray(); var typedArray = Array.CreateInstance(type.GetElementType(), untypedArray.Length); for (var i = 0; i < untypedArray.Length; i++) { typedArray.SetValue(untypedArray[i], i); } return(typedArray); } return(operations.ConvertTo(rubyTypedValue, type)); }
private void btnTest_Click(object sender, EventArgs e) { Reaper RR = new Reaper(); Reaper RR2 = new Reaper(); richTextBox.Clear(); WoTReplay Replay = RR.Parse(@"D:\MyClouds\YandexDisk\wot\REP_Cache\086\086_20130531_2238_uk-GB51_Excelsior_07_lakeville (1).wotreplay"); WoTReplay Replay2 = RR2.Parse(@"D:\MyClouds\YandexDisk\wot\REP_Cache\67690030279124597.wotreplay"); /* * ReplayInfo RI = new ReplayInfo(); * RI.ReadDataFromFile(@"D:\MyClouds\YandexDisk\wot\REP_Cache\086\086_20130531_2238_uk-GB51_Excelsior_07_lakeville (1).wotreplay"); * * ReplayInfo RI2 = new ReplayInfo(); * RI2.ReadDataFromFile(@"D:\MyClouds\YandexDisk\wot\REP_Cache\67690030279124597.wotreplay"); */ // BattleResult_v2 BR = new BattleResult_v2(@"D:\MyClouds\YandexDisk\wot\REP_Cache\!!!\___KV1_321235285635519637.dat"); //BattleResult_v2 BRv2 = new BattleResult_v2(@"D:\MyClouds\YandexDisk\wot\REP_Cache\!!!\82243763184823766.dat"); //KeyValuePair<string, dynamic> /* * foreach (int key in BRv2.Vehicles.Keys) * { * richTextBox.AppendText(BRv2.Players[BRv2.Vehicles[key]["accountDBID"]]["name"]); * if (BRv2.Players[BRv2.Vehicles[key]["accountDBID"]]["clanAbbver"] != "") * { * richTextBox.AppendText("[" + BRv2.Players[BRv2.Vehicles[key]["accountDBID"]]["clanAbbver"] + "]"); * } * richTextBox.AppendText("\n"); * richTextBox.AppendText("---Damage: "+BRv2.Vehicles[key]["damageDealt"]+"\n"); * richTextBox.AppendText("---Team : " + BRv2.Vehicles[key]["team"] + "\n"); * } */ JsonTextReader reader = new JsonTextReader(new StringReader(RR.RawData2)); ////////////////////////////////////////////////////////////////// /// UnPicle ////////////////////////////////////////////////////////////////// ScriptEngine m_engine = Python.CreateEngine(); ScriptScope m_scope = null; m_scope = m_engine.CreateScope(); var paths = new List <string>(); paths.Add(@"C:\Program Files (x86)\IronPython 2.7\Lib"); m_engine.SetSearchPaths(paths); string code = @" import pickle class Serialize(object): def unpickle(self,value): return pickle.loads(value) def unpickledat(self,value): f = open(value,'rb') f.seek(261) bb = f.read() return pickle.loads(bb) "; ObjectOperations ops = m_engine.Operations; ScriptSource source; source = m_engine.CreateScriptSourceFromString(code, SourceCodeKind.Statements); source.Execute(m_scope); object klass = m_scope.GetVariable("Serialize"); object instance = ops.Invoke(klass); object method = ops.GetMember(instance, "unpickle"); object result1 = ops.Invoke(method, (object)RR.RawData3); object result2 = ops.Invoke(method, (object)RR2.RawData3); IronPython.Runtime.PythonDictionary OBJ = (IronPython.Runtime.PythonDictionary)result1; //Dictionary<string, dynamic> D = OBJ.ToDictionary<string, dynamic>(; //double O2 = (double)(((IronPython.Runtime.PythonDictionary)OBJ["common"])["duration"]); //269093955030980.dat //BattleResult BR2 = new BattleResult("D:\\322055057453144847.dat"); string[] LAYOUT = new string[] { "_version", "lastBattleTime", "battleLifeTime", "maxFrags", "xp", "maxXP", "battlesCount", "wins", "losses", "survivedBattles", "winAndSurvived", "frags", "frags8p", "fragsBeast", "shots", "hits", "spotted", "damageDealt", "damageReceived", "treesCut", "capturePoints", "droppedCapturePoints", "sniperSeries", "maxSniperSeries", "invincibleSeries", "maxInvincibleSeries", "diehardSeries", "maxDiehardSeries", "killingSeries", "maxKillingSeries", "piercingSeries", "maxPiercingSeries", "battleHeroes", "fragsSinai", "warrior", "invader", "sniper", "defender", "steelwall", "supporter", "scout", "evileye", "medalKay", "medalCarius", "medalKnispel", "medalPoppel", "medalAbrams", "medalLeClerc", "medalLavrinenko", "medalEkins", "medalWittmann", "medalOrlik", "medalOskin", "medalHalonen", "medalBurda", "medalBillotte", "medalKolobanov", "medalFadin", "medalRadleyWalters", "medalBrunoPietro", "medalTarczay", "medalPascucci", "medalDumitru", "medalLehvaslaiho", "medalNikolas", "medalLafayettePool", "sinai", "heroesOfRassenay", "beasthunter", "mousebane", "tankExpertStrg", "titleSniper", "invincible", "diehard", "raider", "handOfDeath", "armorPiercer", "kamikaze", "lumberjack", "markOfMastery", "company/xp", "company/battlesCount", "company/wins", "company/losses", "company/survivedBattles", "company/frags", "company/shots", "company/hits", "company/spotted", "company/damageDealt", "company/damageReceived", "company/capturePoints", "company/droppedCapturePoints", "clan/xp", "clan/battlesCount", "clan/wins", "clan/losses", "clan/survivedBattles", "clan/frags", "clan/shots", "clan/hits", "clan/spotted", "clan/damageDealt", "clan/damageReceived", "clan/capturePoints", "clan/droppedCapturePoints", "tankExpert", "tankExpert0", "tankExpert1", "tankExpert2", "tankExpert3", "tankExpert4", "tankExpert5", "tankExpert6", "tankExpert7", "tankExpert8", "tankExpert9", "tankExpert10", "tankExpert11", "tankExpert12", "tankExpert13", "tankExpert14", "medalBrothersInArms", "medalCrucialContribution", "medalDeLanglade", "medalTamadaYoshio", "bombardier", "huntsman", "alaric", "sturdy", "ironMan", "luckyDevil", "pattonValley", "fragsPatton", "_dynRecPos_vehicle" }; }
void InitDLR() { try { // Возможно app.config придется упразднять // ?собрать IronPython1C #if (ONEPY45) ScriptRuntimeSetup setup = ScriptRuntimeSetup.ReadConfiguration(Path.Combine(AssemblyDirectory, "OnePy45.dll.config")); #else #if (ONEPY35) ScriptRuntimeSetup setup = ScriptRuntimeSetup.ReadConfiguration(Path.Combine(AssemblyDirectory, "OnePy35.dll.config")); #endif #endif //setup.Options.Add("PreferComDispatch", ScriptingRuntimeHelpers.True); sruntime = new ScriptRuntime(setup); ScriptEngine eng = sruntime.GetEngine("Python"); #region Установка путей поиска модулей var sp = eng.GetSearchPaths(); sp.Add(Environment.CurrentDirectory); sp.Add(Path.Combine(Environment.CurrentDirectory, @"Lib")); sp.Add(Path.Combine(Environment.CurrentDirectory, @"Lib\site-packages")); sp.Add(Path.Combine(Environment.CurrentDirectory, @"IronPython.lib")); sp.Add(Path.Combine(Environment.CurrentDirectory, @"IronPython")); sp.Add(Path.Combine(Environment.CurrentDirectory, @"IronPython\DLLs")); sp.Add(Path.Combine(Environment.CurrentDirectory, @"IronPython\Lib")); sp.Add(Path.Combine(Environment.CurrentDirectory, @"IronPython\Lib\site-packages")); sp.Add(Path.Combine(AssemblyDirectory, @"IronPython.lib")); sp.Add(Path.Combine(AssemblyDirectory, @"IronPython")); sp.Add(Path.Combine(AssemblyDirectory, @"IronPython\DLLs")); sp.Add(Path.Combine(AssemblyDirectory, @"IronPython\Lib")); sp.Add(Path.Combine(AssemblyDirectory, @"IronPython\Lib\site-packages")); foreach (string ap in RuntimeConfig.additional_paths) { sp.Add(ap); } sp.Add(AssemblyDirectory); eng.SetSearchPaths(sp); #endregion ScriptSource conn_src = eng.CreateScriptSource(new AssemblyStreamContentProvider("OnePy.#1"), "cm5ACF5D43F2DA488BB5414714845ACBDE.py"); ScriptSource interf_src = eng.CreateScriptSource(new AssemblyStreamContentProvider("OnePy.#2"), "interfacing.py"); var comp_options = (PythonCompilerOptions)eng.GetCompilerOptions(); comp_options.Optimized = false; comp_options.Module &= ~ModuleOptions.Optimized; interf_scope = eng.CreateScope(); interf_src.Compile(comp_options).Execute(interf_scope); conn_scope = eng.CreateScope(); conn_src.Compile(comp_options).Execute(conn_scope); ops = eng.CreateOperations(); Object calcClass = conn_scope.GetVariable("OnePyConnector"); interactor = new Interactor(); Object calcObj = ops.Invoke(calcClass, interactor); #region Получение ссылок на методы prGetNProps = ops.GetMember <Func <Object, Object> >(calcObj, "GetNProps"); prFindProp = ops.GetMember <Func <Object, Object, Object> >(calcObj, "FindProp"); prGetPropName = ops.GetMember <Func <Object, Object, Object, Object> >(calcObj, "GetPropName"); prGetPropVal = ops.GetMember <Func <Object, Object, Object> >(calcObj, "GetPropVal"); prSetPropVal = ops.GetMember <Func <Object, Object, Object> >(calcObj, "SetPropVal"); prIsPropReadable = ops.GetMember <Func <Object, Object, Object> >(calcObj, "IsPropReadable"); prIsPropWritable = ops.GetMember <Func <Object, Object, Object> >(calcObj, "IsPropWritable"); prGetNMethods = ops.GetMember <Func <Object, Object> >(calcObj, "GetNMethods"); prFindMethod = ops.GetMember <Func <Object, Object, Object> >(calcObj, "FindMethod"); prGetMethodName = ops.GetMember <Func <Object, Object, Object, Object> >(calcObj, "GetMethodName"); prGetNParams = ops.GetMember <Func <Object, Object, Object> >(calcObj, "GetNParams"); prGetParamDefValue = ops.GetMember <Func <Object, Object, Object, Object> >(calcObj, "GetParamDefValue"); prHasRetVal = ops.GetMember <Func <Object, Object, Object> >(calcObj, "HasRetVal"); prCallAsProc = ops.GetMember <Func <Object, Object, Object> >(calcObj, "CallAsProc"); prCallAsFunc = ops.GetMember <Func <Object, Object, Object, Object> >(calcObj, "CallAsFunc"); prCleanAll = ops.GetMember <Func <Object> >(calcObj, "CleanAll"); prAddReferences = ops.GetMember <Func <Object, Object> >(calcObj, "AddReferences"); prClearExcInfo = ops.GetMember <Func <Object> >(calcObj, "ClearExcInfo"); #endregion } catch (Exception e) { ProcessError(e); throw; } }
List <ClassInfo> generateClassInfo() { List <ClassInfo> classInformation = new List <ClassInfo>(); char[] removeEndChars = new char[2] { ',', ' ' }; foreach (KeyValuePair <string, object> obj in objects) { if (obj.Key != "__doc__" && obj.Key != "PythonUnityPrimitive") { if (obj.Value.GetType() == typeof(IronPython.Runtime.Types.OldClass)) // if the object is a class { ClassInfo classInfo = new ClassInfo(); classInfo.name = obj.Key; bool constructor = false; object classObj = obj.Value; foreach (string op in operations.GetMemberNames(classObj)) // for each of its members { string memberSignature = ""; object member = operations.GetMember(classObj, op); if (operations.IsCallable(member) && op != "update") // if it's a function (a method) and not update which is in all classes { if (op == "__init__") // constructor found { memberSignature += classInfo.name + "("; constructor = true; } else { memberSignature += op + "("; constructor = false; } object method = operations.GetMember(member, "__func__"); Type methodType = method.GetType(); PropertyInfo property = methodType.GetProperty("ArgNames", BindingFlags.Instance | BindingFlags.NonPublic); var arguments = property.GetValue(method, null) as string[]; // all parameters to the method foreach (var arg in arguments) // parameters, add to the string for the method { if (arg != "self") { memberSignature += arg + ", "; } } memberSignature = memberSignature.TrimEnd(removeEndChars); memberSignature += ")"; if (constructor) { classInfo.constructorSignature = memberSignature; } else { classInfo.methodSigs.Add(memberSignature); } } } classInformation.Add(classInfo); } } } return(classInformation); }
void InitDLR() { try { // Возможно app.config придется упразднять // ?собрать IronPython1C #if (ONEPY45) ScriptRuntimeSetup setup = ScriptRuntimeSetup.ReadConfiguration(Path.Combine(AssemblyDirectory, "OnePy45.dll.config")); #else #if (ONEPY35) ScriptRuntimeSetup setup = ScriptRuntimeSetup.ReadConfiguration(Path.Combine(AssemblyDirectory, "OnePy35.dll.config")); #endif #endif //setup.Options.Add("PreferComDispatch", ScriptingRuntimeHelpers.True); sruntime = new ScriptRuntime(setup); ScriptEngine eng = sruntime.GetEngine("Python"); #region Установка путей поиска модулей var sp = eng.GetSearchPaths(); sp.Add(Environment.CurrentDirectory); sp.Add(Path.Combine(Environment.CurrentDirectory, @"Lib")); sp.Add(Path.Combine(Environment.CurrentDirectory, @"Lib\site-packages")); sp.Add(Path.Combine(Environment.CurrentDirectory, @"IronPython.lib")); sp.Add(Path.Combine(Environment.CurrentDirectory, @"IronPython")); sp.Add(Path.Combine(Environment.CurrentDirectory, @"IronPython\DLLs")); sp.Add(Path.Combine(Environment.CurrentDirectory, @"IronPython\Lib")); sp.Add(Path.Combine(Environment.CurrentDirectory, @"IronPython\Lib\site-packages")); sp.Add(Path.Combine(AssemblyDirectory, @"IronPython.lib")); sp.Add(Path.Combine(AssemblyDirectory, @"IronPython")); sp.Add(Path.Combine(AssemblyDirectory, @"IronPython\DLLs")); sp.Add(Path.Combine(AssemblyDirectory, @"IronPython\Lib")); sp.Add(Path.Combine(AssemblyDirectory, @"IronPython\Lib\site-packages")); foreach (string ap in RuntimeConfig.additional_paths) { sp.Add(ap); } sp.Add(AssemblyDirectory); eng.SetSearchPaths(sp); #endregion ScriptSource conn_src = eng.CreateScriptSource(new AssemblyStreamContentProvider("OnePy.#1"), "cm5ACF5D43F2DA488BB5414714845ACBDE.py"); ScriptSource interf_src = eng.CreateScriptSource(new AssemblyStreamContentProvider("OnePy.#2"), "interfacing.py"); var comp_options = (PythonCompilerOptions)eng.GetCompilerOptions(); comp_options.Optimized = false; comp_options.Module &= ~ModuleOptions.Optimized; interf_scope = eng.CreateScope(); interf_src.Compile(comp_options).Execute(interf_scope); conn_scope = eng.CreateScope(); conn_src.Compile(comp_options).Execute(conn_scope); ops = eng.CreateOperations(); Object calcClass = conn_scope.GetVariable("OnePyConnector"); interactor = new Interactor(); Object calcObj = ops.Invoke(calcClass, interactor); #region Получение ссылок на методы prGetNProps = ops.GetMember<Func<Object, Object>>(calcObj, "GetNProps"); prFindProp = ops.GetMember<Func<Object, Object, Object>>(calcObj, "FindProp"); prGetPropName = ops.GetMember<Func<Object, Object, Object, Object>>(calcObj, "GetPropName"); prGetPropVal = ops.GetMember<Func<Object, Object, Object>>(calcObj, "GetPropVal"); prSetPropVal = ops.GetMember<Func<Object, Object, Object>>(calcObj, "SetPropVal"); prIsPropReadable = ops.GetMember<Func<Object, Object, Object>>(calcObj, "IsPropReadable"); prIsPropWritable = ops.GetMember<Func<Object, Object, Object>>(calcObj, "IsPropWritable"); prGetNMethods = ops.GetMember<Func<Object, Object>>(calcObj, "GetNMethods"); prFindMethod = ops.GetMember<Func<Object, Object, Object>>(calcObj, "FindMethod"); prGetMethodName = ops.GetMember<Func<Object, Object, Object, Object>>(calcObj, "GetMethodName"); prGetNParams = ops.GetMember<Func<Object, Object, Object>>(calcObj, "GetNParams"); prGetParamDefValue = ops.GetMember<Func<Object, Object, Object, Object>>(calcObj, "GetParamDefValue"); prHasRetVal = ops.GetMember<Func<Object, Object, Object>>(calcObj, "HasRetVal"); prCallAsProc = ops.GetMember<Func<Object, Object, Object>>(calcObj, "CallAsProc"); prCallAsFunc = ops.GetMember<Func<Object, Object, Object, Object>>(calcObj, "CallAsFunc"); prCleanAll = ops.GetMember<Func<Object>>(calcObj, "CleanAll"); prAddReferences = ops.GetMember<Func<Object, Object>>(calcObj, "AddReferences"); prClearExcInfo = ops.GetMember<Func<Object>>(calcObj, "ClearExcInfo"); #endregion } catch (Exception e) { ProcessError(e); throw; } }
/// <summary> /// Execute a script function /// </summary> /// <typeparam name="T"></typeparam> /// <param name="elemt"></param> /// <returns></returns> public static T ExecuteFunction <T>(Model.Element elemt, FunctionOperation funcOp) where T : struct { if (funcOp == FunctionOperation.ForReading) { if (string.IsNullOrWhiteSpace(elemt.Structure.funcr)) { return((T)Convert.ChangeType(elemt.Value, Type.GetTypeCode(typeof(T)))); } } if (funcOp == FunctionOperation.ForWriting) { if (string.IsNullOrWhiteSpace(elemt.Structure.funcw)) { return((T)Convert.ChangeType(elemt.Value, Type.GetTypeCode(typeof(T)))); } } switch (elemt.Type) { case ElementValueType.Float: case ElementValueType.Int: case ElementValueType.Short: case ElementValueType.UInt: case ElementValueType.UShort: break; default: return((T)Convert.ChangeType(elemt.Value, Type.GetTypeCode(typeof(T)))); } // Parse function name ElementValueType string func = elemt.Structure.funcr; if (funcOp == FunctionOperation.ForWriting) { func = elemt.Structure.funcw; } string[] s1 = func.Split('('); string funcName = s1[0]; PyFunctionDefinition pyFunc; if (!_pyDictionary.TryGetValue(funcName, out pyFunc)) { string msg = "ExecuteReadingFunction: The '" + funcName + "' function doesn't exist !!!"; MessageBox.Show(msg, "TESSnip Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return((T)Convert.ChangeType(elemt.Value, Type.GetTypeCode(typeof(T)))); } object function = _objOps.GetMember(_snipClassObj, funcName); // get function // Parse parameters string p = s1[1].Replace("(", "").Replace(")", "").Trim(); var param = new object[0]; if (!string.IsNullOrWhiteSpace(p)) { string[] parameters = p.Split(','); param = new object[parameters.Length]; for (int i = 0; i < parameters.Length; i++) { // management of the decimal separator parameters[i] = parameters[i].Trim(); parameters[i] = parameters[i].Replace(".", _ni.CurrencyDecimalSeparator); parameters[i] = parameters[i].Replace(",", _ni.CurrencyDecimalSeparator); } try { for (int i = 0; i < parameters.Length; i++) { switch (pyFunc.Parameters[i + 3]) //+2 jump self, element and value parameter { case "float": param[i] = float.Parse(parameters[i], _ni); break; case "int": param[i] = int.Parse(parameters[i], _ni); break; case "short": param[i] = short.Parse(parameters[i], _ni); break; case "uint": param[i] = uint.Parse(parameters[i], _ni); break; case "ushort": param[i] = ushort.Parse(parameters[i], _ni); break; } } } catch (Exception ex) { MessageBox.Show(string.Format(@"ExecuteReadingFunction: {0}", ex.Message), @"TESSnip Error", MessageBoxButtons.OK, MessageBoxIcon.Error); throw; } } var result = elemt.Value; try { var el = new PyElement { Name = elemt.Structure.name, Desc = elemt.Structure.desc, CondId = elemt.Structure.CondID, FormIdType = elemt.Structure.FormIDType, Flags = elemt.Structure.flags, Group = elemt.Structure.@group, Multiline = elemt.Structure.multiline, NotInInfo = elemt.Structure.notininfo, Optional = elemt.Structure.optional, Options = elemt.Structure.options, Repeat = elemt.Structure.repeat, FuncRead = elemt.Structure.funcr, FuncWrite = elemt.Structure.funcw, ValueType = elemt.Structure.type }; switch (elemt.Type) { case ElementValueType.Float: result = _objOps.Invoke(function, el, (float)elemt.Value, param); break; case ElementValueType.Int: result = _objOps.Invoke(function, el, (int)elemt.Value, param); break; case ElementValueType.Short: result = _objOps.Invoke(function, el, (short)elemt.Value, param); break; case ElementValueType.UInt: result = _objOps.Invoke(function, el, (uint)elemt.Value, param); break; case ElementValueType.UShort: result = _objOps.Invoke(function, el, (ushort)elemt.Value, param); break; } } catch (Exception ex) { MessageBox.Show(string.Format("ExecuteReadingFunction: {0}", ex.Message), @"TESSnip Error", MessageBoxButtons.OK, MessageBoxIcon.Error); throw; } return((T)Convert.ChangeType(result, Type.GetTypeCode(typeof(T)))); }
public object CallFunction(string name, params object[] parameters) { var fn = _ops.GetMember(_object, name); return(CallFunction(fn, parameters)); }
/// <summary> /// Calls the method. /// </summary> /// <param name="name">Name.</param> public void InvokeMethod(object nameClass, string Method, params object[] parameters) { object Func = Operation.GetMember(nameClass, Method); Operation.Invoke(Func, parameters); }