Non puoi selezionare più di 25 argomenti Gli argomenti devono iniziare con una lettera o un numero, possono includere trattini ('-') e possono essere lunghi fino a 35 caratteri.

PythonScriptInstance.cs 1.7 KiB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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 name, ScriptScope scriptScope)
  10. {
  11. _scriptScope = scriptScope;
  12. Name = name;
  13. }
  14. public string Name { get; }
  15. public bool InvokeOptionalFunction(string name, params object[] parameters)
  16. {
  17. return InvokeOptionalFunction(name, parameters, out _);
  18. }
  19. public bool InvokeOptionalFunction(string name, object[] parameters, out object result)
  20. {
  21. if (name == null) throw new ArgumentNullException(nameof(name));
  22. lock (_scriptScope)
  23. {
  24. if (!_scriptScope.Engine.Operations.TryGetMember(_scriptScope, name, out var member))
  25. {
  26. result = null;
  27. return false;
  28. }
  29. if (!(member is PythonFunction function))
  30. {
  31. throw new Exception($"Member '{name}' is no Python function.");
  32. }
  33. try
  34. {
  35. result = _scriptScope.Engine.Operations.Invoke(function, parameters);
  36. return true;
  37. }
  38. catch (Exception exception)
  39. {
  40. var details = _scriptScope.Engine.GetService<ExceptionOperations>().FormatException(exception);
  41. var message = $"Error while invoking function '{name}'. " + Environment.NewLine + details;
  42. throw new Exception(message, exception);
  43. }
  44. }
  45. }
  46. }
  47. }