選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

PythonScriptInstance.cs 1.8 KiB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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. }