变西瓜 发表于 2025-4-16 19:26:12

C#开发autoCAD调试的时候,每次都要重启autoCAD,很麻烦,求办法解决

Screenager 发表于 2025-4-16 19:26:13

可以使用一个套件来动态加载你的插件using Autodesk.AutoCAD.Runtime;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace ArxDotNetCourse
{
    public class DebugAdapter
    {
      private Action cmd1;
      public DebugAdapter()
      {
            Reload();
      }

      
      public void Cmd1()
      {
            cmd1?.Invoke();
      }

      
      public void Reload()
      {
            FileInfo adapterFileinfo = new FileInfo(Assembly.GetExecutingAssembly().Location);
            string assemblyPath = Path.Combine(adapterFileinfo.DirectoryName, "FunctionalGraph.dll");
            Assembly targetAssembley = Assembly.Load(File.ReadAllBytes(assemblyPath));
            Type targetType = targetAssembley.GetType("FunctionalGraph.Class1");
            MethodInfo targetMethod = targetType.GetMethod("Cmd1");
            Object targetObject = Activator.CreateInstance(targetType);
            cmd1 = () => targetMethod.Invoke(targetObject, null);
      }
    }
}

FishC 发表于 2025-4-16 19:27:12

解决C# AutoCAD调试需频繁重启的两种方案


[*]方案一:使用附加进程调试
1. 在VS中点击 调试 -> 附加到进程
2. 在进程列表中选择正在运行的 acad.exe
3. 修改代码后,按 Ctrl+Shift+B 重新生成DLL
4. 在AutoCAD命令行输入 NETUNLOAD 卸载旧模块
5. 再次输入 NETLOAD 加载新生成的DLL

[*]方案二:自动重载插件(代码实现)
在项目中添加以下命令,执行RELOAD即可热更新:


public void ReloadPlugin()
{
    Assembly assembly = Assembly.GetExecutingAssembly();
    Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
   
    try {
      // 卸载当前程序集
      Application.UnloadApplicationContext(Application.ApplicationContext);
      // 重新加载
      Assembly.Load(File.ReadAllBytes(assembly.Location));
      ed.WriteMessage("\n插件重载成功!");
    }
    catch (Exception ex) {
      ed.WriteMessage("\n错误: " + ex.Message);
    }
}


优化建议

[*]在VS项目属性中设置生成后事件,自动复制DLL到AutoCAD支持路径
[*]将调试启动程序设为 acad.exe 并添加参数 /nologo
[*]使用 AppDomain 隔离加载插件(需要设计分层架构)


提示:NETUNLOAD可能需要处理干净的对象引用,建议在Initialize()中注册的菜单/命令要做成可释放的

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
页: [1]
查看完整版本: C#开发autoCAD调试的时候,每次都要重启autoCAD,很麻烦,求办法解决