【问题标题】:How do I use Matlab engine in my code (for calling `engOpenSingleUse()`)?如何在我的代码中使用 Matlab 引擎(用于调用 `engOpenSingleUse()`)?
【发布时间】:2012-03-28 03:18:49
【问题描述】:

我正在尝试向 Matlab 引擎发送简单的字符串命令。

这是我的代码(除了#include "engine.h" 行之外,我的代码中的其他任何地方都没有与 Matlab API 相关的代码):

void MatlabPlotter::DrawInMatlab() const
{
    std::string PlotCommand = "x=[0 1 2 3 4 5];y=[0 1 4 9 16 25];plot(x, y);";
    void * vpDcom = NULL;
    int iReturnValue;
    engOpenSingleUse(PlotCommand.c_str(), vpDcom, &iReturnValue);
}

代码编译并成功运行,没有任何编译器错误或运行时错误消息。 “Matlab 命令窗口”打开;我得到如下屏幕:

如您所见,命令窗口是空的。屏幕上没有绘图窗口。
当我在这个窗口中手动输入命令时,我得到的绘图没有任何错误,如下所示:

这是engOpenSingleUse()函数的官方文档页面:
http://www.mathworks.com/help/techdoc/apiref/engopensingleuse.html

我在我的项目中添加了 <MatlabInstallationDir>\extern\lib\win64\microsoft\libeng.lib 库(我正在 x64 调试配置中编译)。
我包含了<MatlabInstallationDir>\extern\include\engine.h 头文件。
我在 Matlab 主窗口中输入了!matlab /regserver 命令(如engOpenSingleUse() 函数的文档页面中所述),以确保将 Matlab 引擎注册到我的操作系统。

为什么当我调用engOpenSingleUse() 函数时没有任何反应?
为什么我在PlotCommand对象中发送字符串命令进行绘图时没有弹出绘图窗口?
我做错了什么?

操作系统:Windows 7 Ultimate x64 SP1,最新
IDE:Visual Studio 2010,(版本 10.0.40219.1 SP1Rel)
Matlab:7.8.0(R2009a)

【问题讨论】:

    标签: c++ visual-studio matlab matlab-engine


    【解决方案1】:

    根据您链接到的文档,engOpenSingleUse 的字符串参数是“开始”命令 - 这不是要执行的 MATLAB 命令。 engOpenSingleUse 只是启动 MATLAB 引擎-您必须调用不同的函数才能通过engEvalString

    实际使用引擎
    Engine* matlabEngine = engOpenSingleUse(0, vpDcom, &iReturnValue);
    engEvalString(matlabEngine, PlotCommand.c_str());
    

    engOpenSingleUse 只是表示它启动的引擎只能由一个应用程序使用,不是它将执行单个命令字符串。

    From the docs:

    C 语法

    #include "engine.h"
    Engine *engOpenSingleUse(const char *startcmd, void *dcom,   int *retstatus);
    

    参数:

    startcmd 字符串开始 MATLAB 过程。在 Microsoft Windows 系统上,startcmd 字符串必须 为NULL。

    dcom 保留供将来使用;必须为 NULL。

    retstatus 返回状态;失败的可能原因。

    返回指向引擎的仅限 Microsoft Windows 操作系统的指针 句柄,如果打开失败则为 NULL。

    UNIX 操作系统 UNIX 系统不支持。

    为了完整起见,我要提一下,在继续执行程序之前,您还应该检查以确保 engOpen 调用返回了非 NULL 指针。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-08-13
      • 1970-01-01
      • 2013-05-13
      • 1970-01-01
      • 2011-03-11
      • 1970-01-01
      • 2014-03-17
      相关资源
      最近更新 更多