本文整理汇总了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);
}
}
示例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");
}
示例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;
});
}
示例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);
}
示例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);
}
示例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");
}
示例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");
}
示例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));
}
示例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);
}
示例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));
}
示例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();
}
示例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;
}
示例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;
}
示例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);
}
示例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);
}