当前位置: 首页>>代码示例>>C#>>正文


C# ScriptScope.GetVariable方法代码示例

本文整理汇总了C#中ScriptScope.GetVariable方法的典型用法代码示例。如果您正苦于以下问题:C# ScriptScope.GetVariable方法的具体用法?C# ScriptScope.GetVariable怎么用?C# ScriptScope.GetVariable使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在ScriptScope的用法示例。


在下文中一共展示了ScriptScope.GetVariable方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: PythonSingleLayer

        public PythonSingleLayer(PythonScriptHost host, string code, string name)
        {
            Name = name;
            Code = code;
            Host = host;

            string[] codeWithoutWhitespace = code.Split(new char[] { ' ', '\n' }, StringSplitOptions.RemoveEmptyEntries);
            string alltokens = "";

            foreach (string token in codeWithoutWhitespace)
            {
                alltokens += token;
            }

            _id = alltokens.GetHashCode().ToString();

            _scope = host.CreateScriptSource(code, name);

            if (_scope.ContainsVariable(_processannotations))
            {
                _processAnnotationsFunc = _scope.GetVariable(_processannotations);
            }

            if (_scope.ContainsVariable(_interpret))
            {
                _interpretFunc = _scope.GetVariable(_interpret);
            }
        }
开发者ID:prefab,项目名称:code,代码行数:28,代码来源:PythonSingleLayer.cs

示例2: pyDissector

 public pyDissector(string fileName)
 {
     engine = Python.CreateEngine();
     scope = engine.CreateScope();
     var runtime = engine.Runtime;
     runtime.LoadAssembly(typeof(PacketDotNet.Packet).Assembly);
     runtime.LoadAssembly(typeof(pyDissector).Assembly);
     src = engine.CreateScriptSourceFromFile(fileName);
     program = src.Compile();
     var result = program.Execute(scope);
     var filterString = scope.GetVariable<string>("nativeFilterString");
     myFilter = filterGen.genFilter(filterString);
     parseFunc = scope.GetVariable<Func<Packet, HLPacket>>("parsePacket");
 }
开发者ID:Ronald-Liu,项目名称:visualSniffer,代码行数:14,代码来源:pythonDissector.cs

示例3: PyMovingAverage

        public PyMovingAverage()
        {
            HandlePythonExceptions(() =>
            {
                _engine = Python.CreateEngine();

                var runtime = _engine.Runtime;
                foreach (var reference in GetReferences())
                    runtime.LoadAssembly(reference);

                string code = @"
            import sys
            sys.path.append(r'{0}')
            from MovingAverage import MovingAverage
            expert = MovingAverage()
            ";
                code = string.Format(code, GetBasePath());

                _scope = _engine.CreateScope();
                var source = _engine.CreateScriptSourceFromString(code, SourceCodeKind.Statements);
                source.Execute(_scope);
                _expert = _scope.GetVariable("expert");
                return 0;
            });
        }
开发者ID:sxbailey,项目名称:MQL4,代码行数:25,代码来源:PyMovingAverage.cs

示例4: HookupHandler

        internal void HookupHandler(IBuildProvider provider, ScriptScope moduleGlobals, object self, object target) {

            DynamicFunction scriptFunction = new DynamicFunction((object)moduleGlobals.GetVariable(_handlerName));

            Delegate handler = EventHandlerWrapper.GetWrapper(
                provider, self, scriptFunction, _scriptVirtualPath, typeof(EventHandler));
            _eventInfo.AddEventHandler(target, handler);
        }
开发者ID:nieve,项目名称:ironruby,代码行数:8,代码来源:EventHookupHelper.cs

示例5: DLRType

 /// <summary>
 /// Initializes a new instance of the <see cref="DLRType"/> class.
 /// </summary>
 /// <param name="file">The path to the file.</param>
 /// <param name="scope">The script scope.</param>
 /// <param name="handler">The handler plugin.</param>
 public DLRType(string file, ScriptScope scope, ScriptingPlugin handler)
 {
     File    = file;
     Scope   = scope;
     Handler = handler;
     Name    = Path.GetFileName(file).Replace(".Plugin.py", string.Empty);
     Type    = Scope.GetVariable<Type>(Name);
 }
开发者ID:chiranjeevjain,项目名称:RS-TV-Show-Tracker,代码行数:14,代码来源:DLRType.cs

示例6: IronPython

            static IronPython()
            {
                pythonEngine = Python.CreateEngine();
                pythonScope = pythonEngine.CreateScope();

                var src = pythonEngine.CreateScriptSourceFromString(listisizeCode, SourceCodeKind.Statements);
                src.Execute(pythonScope);

                Listisize = pythonScope.GetVariable<Func<List<List<string>>, List<List<string>>>>("listisize");
            }
开发者ID:tomrittervg,项目名称:Sprocket,代码行数:10,代码来源:TestContext.cs

示例7: InitScripting

        private void InitScripting(string scriptName)
        {
            this.engine = Python.CreateEngine();
            this.engine.Runtime.LoadAssembly(typeof(string).Assembly);
            this.engine.Runtime.LoadAssembly(typeof(DiagnosticMonitor).Assembly);
            this.engine.Runtime.LoadAssembly(typeof(RoleEnvironment).Assembly);
            this.engine.Runtime.LoadAssembly(typeof(Microsoft.WindowsAzure.CloudStorageAccount).Assembly);

            this.scope = this.engine.CreateScope();
            engine.CreateScriptSourceFromFile(scriptName).Execute(scope);

            if (scope.ContainsVariable("start"))
                this.pyStart = scope.GetVariable<Func<bool>>("start");

            this.pyRun = scope.GetVariable<Action>("run");

            if (scope.ContainsVariable("stop"))
                this.pyStop = scope.GetVariable<Action>("stop");
        }
开发者ID:AdamStrojek,项目名称:IronPythonAzure,代码行数:19,代码来源:PyRoleEntryPoint.cs

示例8: PythonInstance

        public PythonInstance(string code, string className = "PyClass")
        {
            //creating engine and stuff
            engine = Python.CreateEngine();
            scope = engine.CreateScope();

            //loading and compiling codes
            source = engine.CreateScriptSourceFromString(code, Microsoft.Scripting.SourceCodeKind.Statements);
            compiled = source.Compile();

            //now executing this code (the code should contain a class)
            compiled.Execute(scope);

            //now creating an object that could be used to access the stuff inside a python script
            pythonClass = engine.Operations.Invoke(scope.GetVariable(className));
        }
开发者ID:inessadl,项目名称:kinect-2-libras,代码行数:16,代码来源:PythonInstance.cs

示例9: GetProperties

        public static bool GetProperties(ScriptScope scriptScope, string method, List<string> properties)
        {
            properties.Clear();

            var m = method.Split('.').ToList();

            if (m.Count() <= 0)
                return false;

            //var s = scriptScope.GetVariable<object>(m[0]);

            var s = scriptScope.GetVariable(m[0]);

            if (null == s)
                return false;

            m.RemoveAt(0);

            return GetProperties(s.GetType(), m, properties);
        }
开发者ID:jpazarzis,项目名称:hogar,代码行数:20,代码来源:AutoCompletion.cs

示例10: PythonInstance

        public PythonInstance(string className = "PyClass")
        {
            string code = @"
            import sys
            sys.path.append(r'C:\Program Files\IronPython 2.7\Lib')
            import os
            import hashlib
            import urllib2
            class PyClass:
            def __init__(self):
            pass

            def somemethod(self):
            print 'in some method'

            def isodd(self, n):
            return 1 == n % 2

            def get_hash(self,name):
            readsize = 64 * 1024
            with open(name, 'rb') as f:
            size = os.path.getsize(name)
            data = f.read(readsize)
            f.seek(-readsize, os.SEEK_END)
            data += f.read(readsize)
            return hashlib.md5(data).hexdigest()
            ";
            //creating engine and stuff
            engine = Python.CreateEngine();
            scope = engine.CreateScope();

            //loading and compiling code
            source = engine.CreateScriptSourceFromString(code, Microsoft.Scripting.SourceCodeKind.Statements);
            compiled = source.Compile();

            //now executing this code (the code should contain a class)
            compiled.Execute(scope);

            //now creating an object that could be used to access the stuff inside a python script
            pythonClass = engine.Operations.Invoke(scope.GetVariable(className));
        }
开发者ID:nalawade41,项目名称:movie-subtitles,代码行数:41,代码来源:movie-sbtitles.cs

示例11: Load

        /// <summary>
        /// Loads this plugin
        /// </summary>
        public void Load()
        {
            // Load the plugin
            string code = File.ReadAllText(Filename);
            Name = Path.GetFileNameWithoutExtension(Filename);
            Scope = PythonEngine.CreateScope();
            var source = PythonEngine.CreateScriptSourceFromString(code, Path.GetFileName(Filename), SourceCodeKind.Statements);
            var compiled = source.Compile();
            compiled.Execute(Scope);
            if (!Scope.ContainsVariable(Name)) throw new Exception("Plugin is missing main class");
            Class = PythonEngine.Operations.CreateInstance(Scope.GetVariable(Name));
            PythonEngine.Operations.SetMember(Class, "Name", Name);

            // Read plugin attributes
            if (!PythonEngine.Operations.ContainsMember(Class, "Title") || PythonEngine.Operations.GetMember<string>(Class, "Title") == null) throw new Exception("Plugin is missing title");
            if (!PythonEngine.Operations.ContainsMember(Class, "Author") || PythonEngine.Operations.GetMember<string>(Class, "Author") == null) throw new Exception("Plugin is missing author");
            if (!PythonEngine.Operations.ContainsMember(Class, "Version") || PythonEngine.Operations.GetMember(Class, "Version").GetType() != typeof(VersionNumber)) throw new Exception("Plugin is missing version");
            Title = PythonEngine.Operations.GetMember<string>(Class, "Title");
            Author = PythonEngine.Operations.GetMember<string>(Class, "Author");
            Version = PythonEngine.Operations.GetMember<VersionNumber>(Class, "Version");
            if (PythonEngine.Operations.ContainsMember(Class, "Description")) Description = PythonEngine.Operations.GetMember<string>(Class, "Description");
            if (PythonEngine.Operations.ContainsMember(Class, "ResourceId")) ResourceId = PythonEngine.Operations.GetMember<int>(Class, "ResourceId");
            HasConfig = PythonEngine.Operations.ContainsMember(Class, "HasConfig") && PythonEngine.Operations.GetMember<bool>(Class, "HasConfig") || PythonEngine.Operations.ContainsMember(Class, "LoadDefaultConfig");

            // Set attributes
            PythonEngine.Operations.SetMember(Class, "Plugin", this);

            Globals = PythonEngine.Operations.GetMemberNames(Class);

            foreach (var name in Globals)
            {
                object func;
                if (!PythonEngine.Operations.TryGetMember(Class, name, out func) || !PythonEngine.Operations.IsCallable(func) || !PythonEngine.Operations.ContainsMember(func, "__dict__")) continue;
                var dict = PythonEngine.Operations.GetMember<PythonDictionary>(func, "__dict__");
                if (dict.ContainsKey("isCommand"))
                {
                    var names = ((IList<object>) dict["name"]).Cast<string>().ToArray();
                    var perms = ((IList<object>) dict["permission"]).Cast<string>().ToArray();
                    if (names.Length == 0)
                    {
                        Interface.Oxide.LogWarning("Command is missing name: {0} from plugin: {1}! Skipping...", name, Name);
                        continue;
                    }
                    AddCovalenceCommand(names, perms, (cmd, type, caller, args) =>
                    {
                        PythonEngine.Operations.InvokeMember(Class, name, caller, args);
                        return true;
                    });
                }
            }

            // Bind any base methods (we do it here because we don't want them to be hooked)
            BindBaseMethods();
        }
开发者ID:CypressCube,项目名称:Oxide,代码行数:57,代码来源:PythonPlugin.cs

示例12: Awakening

        /// <summary>
        /// Starts the $PythonBehaviour
        /// </summary>
        /// <param name="classname">Name of the Script</param>
        public bool Awakening(String classname)
        {
            scope = engine.CreateScope();
            scope.SetVariable("this", this);
            scope.SetVariable("gameObject", gameObject);
            scope.SetVariable("transform", transform);
            scope.SetVariable("enabled", enabled);
            scope.SetVariable("useAPI", new Action(UseAPI));
            scope.SetVariable("disableAPI", new Action(DisableAPI));

            if (Settings.useAPI)
            {
                Besiege.SetUp();
                scope.SetVariable("besiege", Besiege._besiege);
            }
            spaar.ModLoader.Game.OnSimulationToggle += GameOnOnSimulationToggle;
            spaar.ModLoader.Game.OnLevelWon += GameOnOnLevelWon;

            foreach (string @ref in refs.Where(@ref => !String.IsNullOrEmpty(@ref)))
            {
                try
                {

                    #region OBSOLETE
                    /*
                    Assembly assembly = Assembly.Load(@ref);
                    var namespaces = assembly.GetTypes()
                        .Select(t => t.Namespace)
                        .Distinct();
                    String[] lines = Util.splitStringAtNewline(sauce);
                    for (int i = 0; i < lines.Length; i++)
                    {
                        if (!lines[i].Contains("import") && !String.IsNullOrEmpty(lines[i]))
                        {
                            foreach (string ns in namespaces)
                            {
                                if (!String.IsNullOrEmpty(ns))
                                {
                                    if (lines[i].Contains((ns + ".")))
                                    {
                                        lines[i] = Regex.Replace(lines[i], ns + ".", string.Empty);
                                    }
                                }
                            }
                        }
                        lines[i] += Util.getNewLine();
                    }
                    lines = lines.Where(x => !string.IsNullOrEmpty(x) && !x.Equals("\r\n") && !x.Equals("\r") && !x.Equals("\n") && !String.IsNullOrEmpty(x.Trim())).ToArray();
                    sauce = String.Concat(lines);
                    */
                    #endregion

                    engine.Runtime.LoadAssembly(Assembly.Load(@ref));
                }
                catch (Exception ex)
                {
                    Debug.LogException(ex);
                    return false;
                }
            }
            ScriptSource source = engine.CreateScriptSourceFromString(sauce);
            ErrorListener error = new ErrorSinkProxyListener(ErrorSink.Default);
            code = source.Compile(error);
            if (code == null)
            {
                Debug.LogError(error);
                return false;
            }
            code.Execute(scope);
            pythonClass = engine.Operations.Invoke(scope.GetVariable(classname));
            CallMethod("Awake");
            return true;
        }
开发者ID:L3tum,项目名称:BesiegeScriptingMod,代码行数:77,代码来源:PythonBehaviour.cs

示例13: IsSimilarButNotSameAs

        /// <summary>
        /// Check to make sure that two seperate (i.e. not references to same memory) 
        /// ScriptScope objects are equivalent.
        /// 
        /// 1) If they are NOT pointing at the same memory.
        /// 2) If they have the same number of elements and each scope element is the
        ///    same then they are both equal
        internal static bool IsSimilarButNotSameAs(this ScriptScope callingScope, ScriptScope scope)
        {
            // if reference of same object in memory return false
            if (callingScope == scope) return false;

            foreach (string varName in callingScope.GetVariableNames()) {
                if (!scope.ContainsVariable(varName))
                    return false;
                if (scope.GetVariable(varName) != callingScope.GetVariable(varName))
                    return false;
            }

            return true;
        }
开发者ID:TerabyteX,项目名称:main,代码行数:21,代码来源:ScriptScopeTestHelper.cs

示例14: Load

        public override void Load(string code = "")
        {
            Engine = IronPython.Hosting.Python.CreateEngine();
            Scope = Engine.CreateScope();
            Scope.SetVariable("Commands", chatCommands);
            Scope.SetVariable("DataStore", DataStore.GetInstance());
            Scope.SetVariable("Find", Find.GetInstance());
            Scope.SetVariable("GlobalData", GlobalData);
            Scope.SetVariable("Plugin", this);
            Scope.SetVariable("Server", Pluton.Server.GetInstance());
            Scope.SetVariable("ServerConsoleCommands", consoleCommands);
            Scope.SetVariable("Util", Util.GetInstance());
            Scope.SetVariable("Web", Web.GetInstance());
            Scope.SetVariable("World", World.GetInstance());
            try {
                Engine.Execute(code, Scope);
                Class = Engine.Operations.Invoke(Scope.GetVariable(Name));
                Globals = Engine.Operations.GetMemberNames(Class);

                object author = GetGlobalObject("__author__");
                object about = GetGlobalObject("__about__");
                object version = GetGlobalObject("__version__");
                Author = author == null ? "" : author.ToString();
                About = about == null ? "" : about.ToString();
                Version = version == null ? "" : version.ToString();

                State = PluginState.Loaded;
            } catch (Exception ex) {
                Logger.LogException(ex);
                State = PluginState.FailedToLoad;
            }

            PluginLoader.GetInstance().OnPluginLoaded(this);
        }
开发者ID:Viproz,项目名称:Pluton,代码行数:34,代码来源:PYPlugin.cs

示例15: Int

        static void Int(InputData data, Port<int> resp, ScriptScope scope)
        {
           //достаем функцию для интегрирования
           dynamic monte_carlo = scope.GetVariable("monte_carlo");
           //достаем необходимые переменные
           dynamic fun = scope.GetVariable("fun");
           dynamic N = scope.GetVariable("N");
           dynamic result;

           System.Diagnostics.Stopwatch sWatch = new System.Diagnostics.Stopwatch();
           sWatch.Start();

           result = monte_carlo(fun, data.start, data.stop, N);

           sWatch.Stop();
           
           Console.WriteLine("Поток № {0}: Паралл. алгоритм = {1} мс,. Результат: {2}",
           Thread.CurrentThread.ManagedThreadId,
           sWatch.ElapsedMilliseconds.ToString(), result);
           resp.Post(1);
        }
开发者ID:koroboros1,项目名称:TDDP_lab,代码行数:21,代码来源:Program.cs


注:本文中的ScriptScope.GetVariable方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。