Matlab(c) ActiveX 控件的类包装器






4.42/5 (16投票s)
2002 年 9 月 16 日
3分钟阅读

318536

3886
简化了 Matlab(c) COM 服务器的使用...
引言
Matlab(c) 是一款著名的科学软件,涵盖了广泛的工程和数学领域。它还包含一套完整而强大的可视化工具。
Matlab(c) 包含它自己的语言,您可以轻松地在其上开发应用程序。但是,有时您需要从 C/C++ 应用程序运行它,这时一切都变得棘手起来。实际上,虽然 Matlab(c) 附带了 C API,但它使用起来很复杂:链接问题、编译器特殊标志和其他神秘的错误(也许我做错了)。
另一种解决方案是使用 ActiveX 控件的 COM 接口。关于此接口令人遗憾的是...它是 COM,最终你会得到数十行代码... 这就是 CMatlabEngine
发挥作用的地方。它隐藏了所有 COM 代码(获取 CLSID、获取 IDispatch、分配变体、设置函数参数等等),并使您可以专注于工作的主要部分:使用 Matlab(c)。
本文将讨论该类的主要功能,有关更多详细信息,请查看演示项目附带的 Doxygen 文档。请注意,您还可以通过在 MatlabEngine.h 上运行 Doxygen 来生成它。
初始化引擎
所有初始化代码都包含在 CMatlabEngine
的构造函数中。您可以通过调用 IsInitialized
来检查服务器是否已正确初始化
// Initializing COM CoInitialize(NULL); ... // Hooking matlab engine CMatlabEngine mt; if (!mt.IsInitialized()) // could not initialize matlab engine, do something about it
退出应用程序时,不要忘记取消初始化 COM
CoUninitialize();
引擎主要方法
matlab 引擎包含 5 个主要方法:Execute
、PutMatrix
、GetMatrix
、PutString
和 GetString
执行 Matlab(c) 代码
您可以通过调用 Execute( LPCTSTR szMatlabCode )
来执行 Matlab(c) 代码
// this code will show the classic Matlab(c) demo mt.Execute(_T("surf(peaks)")); mt.Execute(_T("title('demo')"));
向 Matlab(c) 发送数组
您可以以向量的形式发送实数或复数数组PutMatrix
发送到 Matlab(c)。请注意,PutMatrix 中的向量必须按行排序:对于大小为 (mxn) 的矩阵 M,M(i,j) 等效于 M[i* n + j]
。
UINT nRows=10; // number of rows UINT nCols=2; // number of columns vector<double> v( nRows * nCols ); // filling up v ... // sending v to Matlab(c) with name "Mv" mt.PutMatrix( _T("M"), v, nRows, nCols); // M is now a matrix in the Matlab(c) workspace
从 matlab 检索数组
您可以通过调用 GetMatrix 检索数组(实数或复数)(它是 PutMatrix 的对偶)
mt.Execute(_T("v=[1 2 3; 4 5 6]';")); vector<double> vReal; UINT nRows, nCols; mt.GetMatrix(_T("v"), nRows, nCols, vReal);
nRows
和 nCols
现在包含数组的维度,而 vReal
包含数据。
将字符串发送到 Matlab(c)
使用 PutString
很容易
mt.PutString("text", "Inserting a string named text");
从 Matlab(c) 获取字符串
使用方法 GetString
LPTSTR szText; // we suppose that myText is a string variable in Matlab mt.GetString("myText",szText);请注意,
szText
由 GetString
在堆上分配,内存清理留给用户。工作区
您可以使用SetWorkspace
修改您正在使用的工作区。 默认情况下,工作区为“base”。 如果要声明全局变量,请使用“global”工作区。处理 Matlab 窗口状态
- 最小化命令窗口,
mt.MinimizeWindow();
- 最大化命令窗口,
mt.MaximizeWindow();
- 显示、隐藏命令窗口,
mt.Show( true /* true to make it visible, false to hide it*/);
- 获取命令窗口的可见性状态,
if(mt.IsVisivle()) // Matlab is server is visible...
- 退出命令窗口,
mt.Quit();
已知错误和限制
Matlab 5.3 及更早版本
Matlab 引擎中的某些函数接口仅在 6.0 版本中引入,因此早于 6.0 的版本的用户在使用该类时会遇到问题。
如果您的 Matlab 早于 v6.0,请取消定义 MatlabEngine.h 开头的 MATLAB_VERSION_6 常量,这将禁用以下函数:IsVisible, Show, PutString, GetString
进一步发展
- 编写
PutCellArray
和GetCellArray
来写入和读取单元格数组。
参考和进一步阅读
- Matlab(c) 外部 API 参考,第 323-328 页
- bin/win32 中的 Matlab 应用程序引擎类型库文件 (
mlapp.tlb
) 可以为您提供接口中实现的可用方法。
修订历史
21-10-2002 | 添加了参考 |
10-09-2002 |
|
09-25-2002 |
|
09-23-2002 |
|