Сборка DLL для запуска python скриптов в AutoCAD - PullRequest
0 голосов
/ 13 февраля 2020

Моя цель - запустить python скрипты в Autocad. Для этого я использую Iron Python 2.7.9 для создания NET API. Сложность заключается в том, что Autocad использует настраиваемые атрибуты для определения команд, поэтому я планирую использовать этот код, который позволяет выбирать и загружать скрипт Python:

using Autodesk.AutoCAD.ApplicationServices;

using Autodesk.AutoCAD.DatabaseServices;

using Autodesk.AutoCAD.Runtime;

using Autodesk.AutoCAD.EditorInput;

using IronPython.Hosting;

using Microsoft.Scripting.Hosting;

using System;



namespace PythonLoader

{

  public class CommandsAndFunctions

  {

    [CommandMethod("-PYLOAD")]

    public static void PythonLoadCmdLine()

    {

      PythonLoad(true);

    }



    [CommandMethod("PYLOAD")]

    public static void PythonLoadUI()

    {

      PythonLoad(false);

    }



    public static void PythonLoad(bool useCmdLine)

    {

      Document doc =

        Application.DocumentManager.MdiActiveDocument;

      Editor ed = doc.Editor;



      short fd =

        (short)Application.GetSystemVariable("FILEDIA");



      // As the user to select a .py file



      PromptOpenFileOptions pfo =

          new PromptOpenFileOptions(

            "Select Python script to load"

          );

      pfo.Filter = "Python script (*.py)|*.py";

      pfo.PreferCommandLine =

        (useCmdLine || fd == 0);

      PromptFileNameResult pr =

        ed.GetFileNameForOpen(pfo);



      // And then try to load and execute it



      if (pr.Status == PromptStatus.OK)

        ExecutePythonScript(pr.StringResult);

    }



    [LispFunction("PYLOAD")]

    public ResultBuffer PythonLoadLISP(ResultBuffer rb)

    {

      const int RTSTR = 5005;



      Document doc =

        Application.DocumentManager.MdiActiveDocument;

      Editor ed = doc.Editor;



      if (rb == null)

      {

        ed.WriteMessage("\nError: too few arguments\n");

      }

      else

      {

        // We're only really interested in the first argument



        Array args = rb.AsArray();

        TypedValue tv = (TypedValue)args.GetValue(0);



        // Which should be the filename of our script



        if (tv != null && tv.TypeCode == RTSTR)

        {

          // If we manage to execute it, let's return the

          // filename as the result of the function

          // (just as (arxload) does)



          bool success =

            ExecutePythonScript(Convert.ToString(tv.Value));

          return

            (success ?

              new ResultBuffer(

                new TypedValue(RTSTR, tv.Value)

              )

              : null);

        }

      }

      return null;

    }



    private static bool ExecutePythonScript(string file)

    {

      // If the file exists, let's load and execute it

      // (we could/should probably add some more robust

      // exception handling here)



      bool ret = System.IO.File.Exists(file);

      if (ret)

      {

        ScriptEngine engine = Python.CreateEngine();

        engine.ExecuteFile(file);

      }

      return ret;

    }

  }

}

сообщение в блоге с кодом

в статье автор говорит, что мне нужно собрать .dll этого скрипта и добавить ссылки на:

IronPython.dll
IronPythonmodules.dll
Microsoft.Scripting.dll
Microsoft.Scripting.Core.dll

и «стандартные ссылки» на

acmgd.dll
acdbmgd.dll

Я скачал декомпилятор и начал искать код для этих .dll, и, конечно, есть много разных частей кода, на которые можно посмотреть. Как выяснить, куда добавить ссылки на скрипт PYLOAD, опубликованные выше, чтобы я мог начать выполнять python сценарии в AutoCAD?

Большое спасибо,

1 Ответ

0 голосов
/ 18 февраля 2020

Сначала вам нужно скомпилировать код. NET, который вы разместили в сборке (например, назовите его «PythonLoader.dll»). Создав сборку из кода PythonLoader, вы можете ссылаться на нее в скрипте PYLOAD Iron Python, загрузив сборку, следуя одному из наборов инструкций здесь . Примеры, приведенные автором, используют clr.AddReferenceToFileAndPath, поэтому я, вероятно, начну с этого.

>>> import clr
>>> clr.AddReferenceToFileAndPath(path_to_PythonLoader.dll)

Обратите внимание, что вам необходимо скомпилировать код. NET для версии . NET Core или. NET Framework, соответствующий версии платформы, на которую ориентирована ваша среда Iron Python. (Из источника Iron Python 2.7.9 похоже, что он нацелен. NET Framework 4.5,. NET Core 2.0 и. NET Core 2.1.)

...