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