You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

外部程序调用iLogic插件遇阻:NamedEntities对象转换失败

解决Inventor iLogic NamedEntities类型转换与访问问题

1. 确认引用iLogic互操作程序集

首先要确保项目中引用了iLogic的COM互操作程序集,默认的Inventor Interop不包含iLogic专属类型(如NamedEntities):

  • 右键项目 → 管理NuGet程序包,搜索Autodesk.Inventor.iLogic.Interop并安装;
  • 或手动添加COM引用:在引用管理器中找到对应Inventor版本的Autodesk iLogic Runtime。

2. 正确获取iLogic Automation实例

之前的代码仅激活了iLogic插件,但未正确获取其Automation接口,这是类型转换失败的核心原因。修改CreateAutomation方法:

private static iLogicAutomation MyAutomation; // 声明为iLogic专属的Automation类型

private static void CreateAutomation()
{
    string iLogicAddinGuid = "{3BDD8D79-2179-4B11-8A5A-257B1C0263AC}";
  
    try
    {
        InventoriLogicAddIn = InventorApplication.ApplicationAddIns.get_ItemById(iLogicAddinGuid);
        if (InventoriLogicAddIn != null)
        {
            if (!InventoriLogicAddIn.Activated)
            {
                InventoriLogicAddIn.Activate();
            }
            // 关键步骤:获取iLogic的Automation接口实例
            MyAutomation = (iLogicAutomation)InventoriLogicAddIn.Automation;
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine($"获取iLogic Automation失败: {ex.Message}");
        throw;
    }
}

3. 强类型访问NamedEntities

引用iLogic Interop后,即可直接强类型接收并遍历NamedEntities:

// 基于已加载的CurrentDocument获取命名实体
NamedEntities nameList = MyAutomation.GetNamedEntities(CurrentDocument);

// 遍历所有命名实体,过滤出面类型对象
foreach (NamedEntity entity in nameList)
{
    if (entity.ObjectType == ObjectTypeEnum.kFaceObject)
    {
        Console.WriteLine($"面名称: {entity.Name}");
        // 转换为Inventor Face对象,用于后续关联逻辑
        Face targetFace = (Face)entity.Object;
    }
}

4. 无互操作引用时的反射备选方案

如果无法引用iLogic Interop,可通过反射访问dynamic对象的属性与集合:

dynamic nameList = MyAutomation.GetNamedEntities(CurrentDocument);

// 通过反射获取集合元素数量(Inventor集合为1-based索引)
int entityCount = (int)nameList.GetType().InvokeMember("Count", BindingFlags.GetProperty, null, nameList, null);

for (int i = 1; i <= entityCount; i++)
{
    dynamic entity = nameList.GetType().InvokeMember("Item", BindingFlags.GetProperty, null, nameList, new object[] { i });
    // 过滤面类型实体
    if ((int)entity.ObjectType == (int)Inventor.ObjectTypeEnum.kFaceObject)
    {
        string faceName = (string)entity.GetType().InvokeMember("Name", BindingFlags.GetProperty, null, entity, null);
        Console.WriteLine($"面名称: {faceName}");
        Inventor.Face targetFace = (Inventor.Face)entity.Object;
    }
}

常见排查点

  • 确保Inventor版本与引用的互操作程序集版本完全匹配;
  • 以管理员身份运行程序,避免COM对象访问权限问题;
  • 确认零件文档中存在已命名的面(未命名面不会出现在NamedEntities集合中)。

内容的提问来源于stack exchange,提问作者abbahex

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 22:28:22