Modelica外部函数多输出实现:无需Record可行吗?
Modelica外部函数多输出实现方案(含无Record/用Record两种方式)
问题分析
你当前的代码编译报错dsmodel.c(69): error C2198: 'three_Out': too few arguments for call,核心原因是:Modelica外部函数的多输出不能直接像原生Modelica函数那样返回,必须通过C语言指针参数传递——你在external调用里没把输出变量的指针传进C函数,导致参数数量不匹配。
一、不使用Record的正确实现
这是最直接的方式,核心是在external调用中把输出变量以指针引用的形式加入参数列表,对应C函数的指针参数。
修正后的完整代码:
model ExampleMultipleOutputs "Example model to output multiple values" parameter Real a = 1 "Example real parameter"; parameter Integer b = 2 "Example integer parameter"; Real y1 "Declare output y1"; Real y2 "Declare output y2"; Real y3 "Declare output y3"; protected function threeOut "Output three Real values from external function" input Real a; input Integer b; output Real y1 "Output 1"; output Real y2 "Output 2"; output Real y3 "Output 3"; // 关键修正:添加输出变量的指针引用到external参数列表 external"C" three_Out(a, b, &y1, &y2, &y3); annotation ( Include=" void three_Out(double a, int b, double* y1, double* y2, double* y3){ *y1 = a; *y2 = (double)b; // 显式转double,避免类型不匹配警告 *y3 = a + a; } "); end threeOut; equation (y1, y2, y3) = threeOut(a=a, b=b); end ExampleMultipleOutputs;
关键修正点
- Modelica的
external调用必须按「输入参数 → 输出指针参数」的顺序传递所有参数 - C函数通过指针修改外部变量的值,实现“返回”多输出的效果
- 把int类型的
b转为double再赋值给y2,避免编译警告
二、使用Record的实现方法
如果需要把多输出打包成一个整体,可以用Record类型,本质是用C结构体对应Modelica的Record。
完整代码示例:
model ExampleMultipleOutputsWithRecord parameter Real a = 1; parameter Integer b = 2; Real y1, y2, y3; protected // 1. 定义封装多输出的Record record Outputs Real y1; Real y2; Real y3; end Outputs; function threeOutWithRecord input Real a; input Integer b; output Outputs res; // 传入Record变量的指针 external"C" three_Out_Record(a, b, &res); annotation ( Include=" // C结构体必须和Modelica Record的字段名、类型完全匹配 typedef struct { double y1; double y2; double y3; } Outputs; void three_Out_Record(double a, int b, Outputs* res){ res->y1 = a; res->y2 = (double)b; res->y3 = a + a; } "); end threeOutWithRecord; equation // 2. 调用后直接解构Record为单个变量 (y1, y2, y3) = threeOutWithRecord(a, b); end ExampleMultipleOutputsWithRecord;
注意事项
- Modelica Record会被Dymola自动映射为C结构体,字段名、类型必须严格对应,不能出错
- C函数通过结构体指针修改内部字段的值,实现多输出打包返回
- 调用后可以直接用解构语法把Record拆成单个变量使用
内容的提问来源于stack exchange,提问作者moored6
相关产品推荐
相关产品推荐

