在实际项目中偶尔会遇到这个使用场景,但是频率不高,小记一下
🖥️C#关键代码
通过 System.Diagnostics.Process
启动进程并传参:
// 1. 配置启动参数
var startInfo = new ProcessStartInfo
{
FileName = @"C:\Path\To\Your\MatlabApp.exe", // 替换为你的EXE路径
Arguments = "123 \"Hello World\"", // 传递参数(数值+字符串)
UseShellExecute = false, // 不使用系统Shell
RedirectStandardOutput = true, // 重定向标准输出
RedirectStandardError = true, // 重定向错误输出
CreateNoWindow = true // 不创建窗口(静默运行)
};
// 2. 创建并启动进程
using (var process = new Process { StartInfo = startInfo })
{
process.Start();
// 3. 读取输出(异步避免死锁)
string output = process.StandardOutput.ReadToEnd();
string error = process.StandardError.ReadToEnd();
// 4. 等待程序退出(可设置超时时间)
process.WaitForExit();
// 5. 处理结果
Console.WriteLine($"Exit Code: {process.ExitCode}");
Console.WriteLine("Output: " + output);
if (!string.IsNullOrEmpty(error))
Console.Error.WriteLine("Errors: " + error);
}
🔎MATLAB关键代码
在 MATLAB
入口函数中接收参数:
function main(varargin)
if nargin == 0
msgbox("没有参数传入");
else
text = "收到参数:";
for i = 1:nargin
text = text + newline + sprintf("参数 %d: %s", i, varargin{i});
end
msgbox(text, '参数显示');
end
end
⚠️注意事项
参数传递规则
多个参数用空格分隔
含空格的字符串需用双引号包裹(如
"C:\My Data\file.txt"
)MATLAB接收的参数均为字符串,需自行转换类型
路径问题
使用绝对路径避免歧义
特殊字符需转义(如
\
在C#中需写为\\
)
部署依赖
确保目标机器安装匹配版本的
MATLAB Runtime
首次运行会自动提示下载或通过
MCRInstaller.exe
安装