// 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)); }
private PythonObject() { _pi.Execute("class _TempObj(object): pass"); var objectType = _pi.GetVariable("_TempObj"); _object = _ops.Invoke(objectType); }
// call python method 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); } }
public Func <object, Task <object> > CompileFunc(IDictionary <string, object> parameters) { string source = this.NormalizeSource((string)parameters["source"]); bool sync = false; object tmp; if (parameters.TryGetValue("sync", out tmp)) { sync = (bool)tmp; } // Compile to a Python lambda expression ScriptEngine engine = Python.CreateEngine(); ScriptSource script = engine.CreateScriptSourceFromString(source, "path-to-py"); PythonFunction pythonFunc = script.Execute() as PythonFunction; if (pythonFunc == null) { throw new InvalidOperationException("The Python code must evaluate to a Python lambda expression that takes one parameter, e.g. `lambda x: x + 1`."); } ObjectOperations operations = engine.CreateOperations(); // create a Func<object,Task<object>> delegate around the method invocation using reflection if (sync) { return((input) => { object ret = operations.Invoke(pythonFunc, new object[] { input }); return Task.FromResult <object>(ret); }); } else { return((input) => { var task = new Task <object>(() => { object ret = operations.Invoke(pythonFunc, new object[] { input }); return ret; }); task.Start(); return task; }); } }
///////////////////////////////////////////////////////////////////////////// public BattleResult_v2(string path) { var paths = new List <string>(); paths.Add(@"C:\Program Files (x86)\IronPython 2.7\Lib"); ScriptEngine m_engine = Python.CreateEngine(); ScriptScope m_scope = null; m_scope = m_engine.CreateScope(); m_engine.SetSearchPaths(paths); ObjectOperations ops = m_engine.Operations; Assembly assembly = Assembly.GetExecutingAssembly(); string name = "CacheReaper.Scripts.Serialize.py"; Stream stream = assembly.GetManifestResourceStream(name); StreamReader textStreamReader = new StreamReader(stream); string code = textStreamReader.ReadToEnd(); ScriptSource source = m_engine.CreateScriptSourceFromString(code, SourceCodeKind.Statements); source.Execute(m_scope); dynamic Serialize = ops.Invoke(m_scope.GetVariable("Serialize")); dynamic result = Serialize.unpickle((object)path); __arenaUniqueID = (long)((BigInteger)result[1][0]); __personalResult = SetPersonalData(result[1][1]); __common = SetCommonData(result[1][2][0]); __players = SetPlayersData(result[1][2][1]); __vehicles = SetVehiclesData(result[1][2][2]); }
public object InvokeFunction(string name, params object[] parameters) { if (name == null) { throw new ArgumentNullException(nameof(name)); } object result; lock (_syncRoot) { try { if (!_functionsCache.TryGetValue(name, out var pythonFunction)) { throw new PythonProxyException($"Python function '{name}' not found."); } var pythonParameters = parameters?.Select(PythonConvert.ToPython).ToArray() ?? _emptyParameters; result = _operations.Invoke(pythonFunction, pythonParameters); } catch (Exception exception) { var details = _scriptScope.Engine.GetService <ExceptionOperations>().FormatException(exception); var message = $"Error while Python invoking function '{name}'. " + Environment.NewLine + details; throw new PythonProxyException(message, exception); } } return(result); }
public string Invoke(string input) { object ret = _operations.Invoke(_pythonFunc, new object[] { input }); var task = Task.FromResult(ret); task.Wait(); return(task.Result as string); }
/// <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 BattleResult(string path) { var paths = new List <string>(); paths.Add(@"C:\Program Files (x86)\IronPython 2.7\Lib"); ScriptEngine m_engine = Python.CreateEngine(); ScriptScope m_scope = null; m_scope = m_engine.CreateScope(); m_engine.SetSearchPaths(paths); ObjectOperations ops = m_engine.Operations; Assembly assembly = Assembly.GetExecutingAssembly(); string name = "CacheReaper.Scripts.Serialize.py"; Stream stream = assembly.GetManifestResourceStream(name); StreamReader textStreamReader = new StreamReader(stream); string code = textStreamReader.ReadToEnd(); ScriptSource source = m_engine.CreateScriptSourceFromString(code, SourceCodeKind.Statements); source.Execute(m_scope); dynamic Serialize = ops.Invoke(m_scope.GetVariable("Serialize")); dynamic result = Serialize.unpickle((object)path); //IList<object> Temp_1 = result[1]; //IList<object> Temp_1_2 = result[1][2]; _arenaUniqueID = result[1][0]; _personalResult = new PersonalData(result[1][1]); _common = new CommonData(result[1][2][0]); _players = new Dictionary <int, PlayerData>(); PlayerData _player; foreach (KeyValuePair <object, object> kvp in (PythonDictionary)result[1][2][1]) { _player = new PlayerData((IList <object>)kvp.Value); _players.Add((int)kvp.Key, _player); } PersonalData _vehicle; _vehicles = new Dictionary <int, PersonalData>(); foreach (KeyValuePair <object, object> kvp in (PythonDictionary)result[1][2][2]) { _vehicle = new PersonalData((IList <object>)kvp.Value); _vehicles.Add((int)kvp.Key, _vehicle); } int x = 0; }
/// <summary> /// Init the py interpreter /// </summary> public static void InitPyInterpreter() { System.Globalization.CultureInfo ci = System.Globalization.CultureInfo.InstalledUICulture; _ni = (System.Globalization.NumberFormatInfo)ci.NumberFormat.Clone(); _ni.NumberDecimalSeparator = "."; _pyEngine = Python.CreateEngine(); // Create an engine to access IronPython _objOps = _pyEngine.CreateOperations(); // Performing tasks with the script _scope = _pyEngine.CreateScope(); // Default scope for executing the script _source = _pyEngine.CreateScriptSourceFromFile(ScriptsPyPath); // Load the script _compiledCode = _source.Compile(); _compiledCode.Execute(_scope); // Create class object _snipClass = _scope.GetVariable("SnipClass"); // Retrieve the class object _snipClassObj = _objOps.Invoke(_snipClass); // Create an instance of the SnipClass _pyDictionary = new Dictionary <string, PyFunctionDefinition>(); LoadAllPrototypeFunction(); }
public static void Reload() { try { source = pyEngine.CreateScriptSourceFromFile(RendererPyPath); // Load the script compiledCode = source.Compile(); compiledCode.Execute(scope); // Create class object rendererClass = scope.GetVariable("Renderer"); // Retrieve the class object if (rendererClass != null) { rendererImpl = objOps.Invoke(rendererClass) as IRenderer; // Create an instance of the Renderer } } catch (Exception) { source = null; compiledCode = null; rendererClass = null; rendererImpl = null; } }
internal static FScheme.Value convertToValue(dynamic data, ObjectOperations invoker) { if (data is FScheme.Value) return data; else if (data is string) return FScheme.Value.NewString(data); else if (data is double || data is int || data is float) return FScheme.Value.NewNumber(data); else if (data is IEnumerable<dynamic>) { FSharpList<FScheme.Value> result = FSharpList<FScheme.Value>.Empty; //data.reverse(); // this breaks under certain circumstances var reversalList = new List<dynamic>(); foreach (var x in data) { reversalList.Add(x); } for (int i = reversalList.Count - 1; i >= 0; --i) { var x = reversalList[i]; result = FSharpList<FScheme.Value>.Cons(convertToValue(x, invoker), result); } //foreach (var x in data) //{ // result = FSharpList<FScheme.Value>.Cons(convertToValue(x), result); //} return FScheme.Value.NewList(result); } else if (data is PythonFunction) { return FScheme.Value.NewFunction( Utils.ConvertToFSchemeFunc( args => convertToValue( invoker.Invoke( data, args.Select(x => convertFromValue(x, invoker) as object) .ToArray()), invoker))); } else if (data is PyWrapper) { var func = data as PyWrapper; return FScheme.Value.NewFunction( Utils.ConvertToFSchemeFunc( args => convertToValue( func(args.Select(a => convertFromValue(a, invoker)).ToArray()), invoker))); } else return FScheme.Value.NewContainer(data); }
/// <summary> /// Gets the variable or class /// </summary> /// <returns>The variable.</returns> /// <param name="name">Name.</param> public object GetVariable(string name) { return(Operation.Invoke(Scope.GetVariable(name))); }
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; } }
internal static FScheme.Value convertToValue(dynamic data, ObjectOperations invoker) { if (data is FScheme.Value) { return(data); } else if (data is string) { return(FScheme.Value.NewString(data)); } else if (data is double || data is int || data is float) { return(FScheme.Value.NewNumber(data)); } else if (data is IEnumerable <dynamic> ) { FSharpList <FScheme.Value> result = FSharpList <FScheme.Value> .Empty; //data.reverse(); // this breaks under certain circumstances var reversalList = new List <dynamic>(); foreach (var x in data) { reversalList.Add(x); } for (int i = reversalList.Count - 1; i >= 0; --i) { var x = reversalList[i]; result = FSharpList <FScheme.Value> .Cons(convertToValue(x, invoker), result); } //foreach (var x in data) //{ // result = FSharpList<FScheme.Value>.Cons(convertToValue(x), result); //} return(FScheme.Value.NewList(result)); } else if (data is PythonFunction) { return (FScheme.Value.NewFunction( Utils.ConvertToFSchemeFunc( args => convertToValue( invoker.Invoke( data, args.Select(x => convertFromValue(x, invoker) as object) .ToArray()), invoker)))); } else if (data is PyWrapper) { var func = data as PyWrapper; return (FScheme.Value.NewFunction( Utils.ConvertToFSchemeFunc( args => convertToValue( func(args.Select(a => convertFromValue(a, invoker)).ToArray()), invoker)))); } else { return(FScheme.Value.NewContainer(data)); } }
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)))); }