NX二次开发:递归遍历特征组并收集所有特征

1. 引言

在NX二次开发中,特征组(GroupFeature)允许用户将多个特征组织在一起,便于管理和操作。当需要遍历部件中的所有特征时,如果只获取顶层特征列表,会遗漏特征组内部的子特征。本文介绍一种递归遍历方法,能够完整收集特征组及其嵌套子特征。

2. 核心实现

核心思路是:先获取部件中的所有顶层特征,然后对每个特征判断是否为特征组;如果是特征组,则递归获取其子特征,直到所有嵌套层级都被遍历完毕。

3. 代码实现

下面给出完整的递归遍历实现代码。

cpp 复制代码
void CFeatureFunction::RecursiveCollectGroupChildren(std::map<NXOpen::Features::Feature*, std::string>& outAllFeatures,
                                                     std::vector<NXOpen::Features::Feature*> inFeats)
{
    for (NXOpen::Features::Feature* feat : inFeats)
    {
        char name[100] = { 0 };
        UF_OBJ_ask_name(feat->Tag(), name);
        std::string nameStr = name;
        outAllFeatures[feat] = nameStr;

        // 判断是否是特征组
        NXOpen::Features::GroupFeature* groupFeat = dynamic_cast<NXOpen::Features::GroupFeature*>(feat);
        if (groupFeat != nullptr)
        {
            // 获取组里面所有子特征,递归
            std::vector<NXOpen::Features::Feature*> children = groupFeat->GetChildren();
            RecursiveCollectGroupChildren(outAllFeatures, children);
        }
    }
}

// 对外入口
void CFeatureFunction::RecursiveCollectGroupChildren(std::map<NXOpen::Features::Feature*, std::string>& outAllFeatures)
{
    Session* theSession = Session::GetSession();
    Part* workPart = theSession->Parts()->Work();
    std::vector<NXOpen::Features::Feature*> allTopFeats = workPart->Features()->GetFeatures();
    RecursiveCollectGroupChildren(outAllFeatures, allTopFeats);
}

4. 关键点说明

上述实现中有几个关键点值得注意:

  • 动态类型判断 :通过 dynamic_cast 判断特征是否为 GroupFeature,这是递归能否深入特征组内部的前提。
  • 递归终止条件 :当某个特征不是特征组时,递归自然终止;特征组内没有子特征时,GetChildren() 返回空列表,循环结束。
  • 名称获取 :使用 UF_OBJ_ask_name 获取特征名称,注意缓冲区大小要足够容纳名称字符串。

5. 全部特征收集

返回部件中全部的特征 。 注意:这是一个底层接口,它会返回一部分在 NX 界面上看不到、部件导航器浏览不到的内部隐藏特征。

cpp 复制代码
void CFeatureFunction::CollectAllFeatures(std::map<NXOpen::Features::Feature*, std::string>& outAllFeatures)
{
    Session* theSession = Session::GetSession();
    Part* workPart = theSession->Parts()->Work();
    std::vector<NXOpen::Features::Feature*> allTopFeats = workPart->Features()->GetFeatures();
    for (NXOpen::Features::Feature* topFeat : allTopFeats)
    {
        char name[100] = { 0 };
        UF_OBJ_ask_name(topFeat->Tag(), name);
        std::string nameStr = name;
        outAllFeatures[topFeat] = nameStr;
    }
}

6. 总结

通过递归遍历特征组,可以完整收集部件中的所有特征,包括嵌套在特征组内部的子特征。这种方法适用于需要全量处理特征的场景,例如批量导出特征信息、特征重命名或特征状态检查等。

相关推荐
xier_ran4 小时前
【infra之路】AI 编译器学习笔记(六):重拾 C++——lambda 与 MLIR 中的回调
c++·笔记·学习
jimy16 小时前
c++的 Type Traits (一)
开发语言·c++
别动我齐刘海7 小时前
Linux 系统调试学习2
linux·运维·c++·人工智能·学习·机器学习·机器人
ZZHow10248 小时前
Ascend C算子开发(高级)笔记
c++·人工智能·笔记·深度学习·华为云
aqiu1111118 小时前
【C++算法打怪专栏】LeetCode 217. 存在重复元素(解法总结)
c++·算法·leetcode
lojox9 小时前
深入理解 C++ STL:vector 底层实现、迭代器失效与 list 特性
开发语言·c++
微笑星河q9 小时前
C++类和对象(下)初始化列表、类型转换、static、友元、内部类、匿名对象
开发语言·c++
|_⊙10 小时前
C++ 类和对象零散知识点
开发语言·c++
xiangyun6110 小时前
C++ list 模拟实现(二):const迭代器与反向迭代器,模板的黑魔法
开发语言·数据库·c++·算法·stl·list
坤坤子吖11 小时前
Linux 进程信号入门——从 Ctrl+C 到 kill
linux·开发语言·c++·笔记·学习