if (build == true)
{
// 连接到正在运行的 SAP2000
// 使用 System.Runtime.InteropServices.Marshal.GetActiveObject 方法获取正在运行的 SAP2000 实例
cOAPI mySapObject = (cOAPI)System.Runtime.InteropServices.Marshal.GetActiveObject("CSI.SAP2000.API.SapObject");
// 获取 SAP2000 模型对象
cSapModel mySapModel = mySapObject.SapModel;
// 运行 SAP2000 分析
//mySapModel.Analyze.RunAnalysis();
// 启动钢结构设计
//mySapModel.DesignSteel.StartDesign();
// 获取所有框架单元的总数
int numberFrames = 0;
string[] frameNames = null;
// 使用 ref 关键字传递参数,以便在函数内部修改参数的值
mySapModel.FrameObj.GetNameList(ref numberFrames, ref frameNames);
// 声明应力比列表
List<double> _ratios = new List<double>();
// 遍历所有单元
for (int i = 0; i < numberFrames; i++)
{
string frameName = frameNames[i];
// 获取当前框架单元的应力比
int NumberItems = 0;
string[] FrameName = new string[0];
double[] Ratio = new double[0];
int[] RatioType = new int[0];
double[] Location = new double[0];
string[] ComboName = new string[0];
string[] ErrorSummary = new string[0];
string[] WarningSummary = new string[0];
// 使用 ref 关键字传递参数,以便在函数内部修改参数的值
mySapModel.DesignSteel.GetSummaryResults(frameName, ref NumberItems, ref FrameName, ref Ratio, ref RatioType, ref Location, ref ComboName, ref ErrorSummary, ref WarningSummary);
// 检查是否有应力比结果
if (NumberItems > 0)
{
// 取控制应力比(第一个结果)
_ratios.Add(Ratio[0]);
}
else
{
// 如果没有结果,添加0
_ratios.Add(0);
}
}
// 删除第一个 <null> 值(如果存在)
if (_ratios.Count > 0 && _ratios[0] == 0)
{
_ratios.RemoveAt(0);
}
// 查找名为 "StressRatios" 的输出参数的索引
int outputIndex = -1;
// 使用 for 循环遍历输出参数列表
for (int i = 0; i < Component.Params.Output.Count; i++)
{
// 比较输出参数的 NickName 属性与目标输出参数名称
if (Component.Params.Output[i].NickName == "StressRatios")
{
outputIndex = i;
// 使用 break 语句退出循环,提高效率
break;
}
}
// 如果找到了 "StressRatios" 输出参数
if (outputIndex >= 0)
{
// 将应力比列表赋值给 "StressRatios" 输出参数
Component.ExpireSolution(true);
// 使用索引访问输出参数,并调用 AddVolatileDataList 方法将数据赋值给输出参数
Component.Params.Output[outputIndex].AddVolatileDataList(new Grasshopper.Kernel.Data.GH_Path(0), _ratios);
}
}
使用的编程技巧说明:
-
使用
System.Runtime.InteropServices.Marshal.GetActiveObject
方法获取正在运行的 SAP2000 实例,避免重复打开 SAP2000 程序。 -
使用
ref
关键字传递参数,以便在函数内部修改参数的值,提高代码的可读性和效率。 -
使用
for
循环遍历输出参数列表,通过比较输出参数的NickName
属性与目标输出参数名称来查找指定输出参数的索引。 -
在找到目标输出参数后,使用
break
语句退出循环,提高代码的效率。 -
使用索引访问输出参数,并调用
AddVolatileDataList
方法将数据赋值给输出参数,确保数据能够正确传递给 Grasshopper 组件的输出端口。 -
使用条件语句
if (build == true)
控制代码的执行,避免不必要的计算和操作。 -
使用列表
List<double> _ratios
存储应力比结果,方便后续的数据处理和操作。 -
使用条件语句
if (_ratios.Count > 0 && _ratios[0] == 0)
删除列表中的第一个<null>
值(如果存在),确保数据的准确性和完整性。
效果