您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符
 
 
 
 

61 行
1.8 KiB

  1. using System;
  2. using IronPython.Runtime;
  3. using Microsoft.Scripting.Hosting;
  4. namespace MQTTnet.Server.Scripting
  5. {
  6. public class PythonScriptInstance
  7. {
  8. private readonly ScriptScope _scriptScope;
  9. public PythonScriptInstance(string uid, string path, ScriptScope scriptScope)
  10. {
  11. Uid = uid;
  12. Path = path;
  13. _scriptScope = scriptScope;
  14. }
  15. public string Uid { get; }
  16. public string Path { get; }
  17. public bool InvokeOptionalFunction(string name, params object[] parameters)
  18. {
  19. return InvokeOptionalFunction(name, parameters, out _);
  20. }
  21. public bool InvokeOptionalFunction(string name, object[] parameters, out object result)
  22. {
  23. if (name == null) throw new ArgumentNullException(nameof(name));
  24. lock (_scriptScope)
  25. {
  26. if (!_scriptScope.Engine.Operations.TryGetMember(_scriptScope, name, out var member))
  27. {
  28. result = null;
  29. return false;
  30. }
  31. if (!(member is PythonFunction function))
  32. {
  33. throw new Exception($"Member '{name}' is no Python function.");
  34. }
  35. try
  36. {
  37. result = _scriptScope.Engine.Operations.Invoke(function, parameters);
  38. return true;
  39. }
  40. catch (Exception exception)
  41. {
  42. var details = _scriptScope.Engine.GetService<ExceptionOperations>().FormatException(exception);
  43. var message = $"Error while invoking function '{name}'. " + Environment.NewLine + details;
  44. throw new Exception(message, exception);
  45. }
  46. }
  47. }
  48. }
  49. }