gpt4 book ai didi

c++ - MATLAB mex API 与 MATLAB 引擎 API 之间的区别

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:48:08 25 4
gpt4 key购买 nike

我在通过 matlab 的引擎 API 获取(并因此设置)图形对象的属性时遇到困难:我总是在以下代码中获取 NULL 指针(我在 Windows 8.1 上使用 R2015b):

#include <engine.h>
#include <matrix.h>
#include <mex.h>
#include <mat.h>
int main()
{
Engine *MATLAB;
if (!(MATLAB = engOpen(NULL)))
{
//exit failure etc.
}
engEvalString(MATLAB, "clearvars;close all;x=linspace(-pi,pi);figure;h=plot(x,sin(x),'o-b','LineWidth',2.5);");//OK!! got the plot on a new figure
const mxArray *ph = engGetVariable(MATLAB, "h");//OK!!
const char *cname = mxGetClassName(ph);// OK!!!: got cname = matlab.graphics.chart.primitive.Line
size_t ind = 0;
const char *Prop = "LineWidth";
mxArray *p = mxGetProperty(ph,ind,Prop);//bummer !!! - p is always NULL!!
return 0;
}

现在,当使用 mex API 编写等效代码时,一切正常,如下所示:

1:正在运行下一个 MATLAB 脚本:

mex getMex.cpp;%compile getMex.cpp (with VS 2010 Ultimate), see code below
clearvars;close all;x=linspace(-pi,pi);figure;h=plot(x,sin(x),'o-b','LineWidth',2.5);%OK!! got the plot on a new figure
LineWidth = getMex(h);% OK!! LineWidth = 2.5

getMex.cpp 源文件:

#include "mex.h"
void mexFunction(int nlhs, mxArray *plhs[], int nrhs,
const mxArray *prhs[])
{
//some input/output checks here
mxArray *p = mxGetProperty(prhs[0],0,"LineWidth"); //OK!!! - not NULL
double *p2h=mxGetPr(p);//OK!!! *p2h = 2.5
plhs[0] = p;
}

在 VS 2010 中调试 mex 代码和引擎代码时,我看到了完全加载了相同的 dll。

我的引擎 API 代码有什么问题?

我在这里错过了什么?

最佳答案

好吧,显然这是不可能的 )-: ,这是我从 mathworks 支持部门得到的答案:

You cannot use MEX API functions in C/C++ MATLAB Engine code. Customers can use the MEX API to call C, C++, or Fortran code from a MATLAB script. The MATLAB Engine API enables the opposite interaction between MATLAB and C/C++. Using the MATLAB Engine, customers can leverage the functionality of MATLAB in C or C++ code. The distinction between the two APIs explains why "mxGetProperty", a MEX API function, returns the correct value for "LineWidth" in your MEX file "getMex.cpp", but returns NULL in the MATLAB Engine implementation.

Nevertheless, your use case brought to light two current discrepancies in MATLAB:

  1. Our documentation does not state that the MEX API should not be used in the context of the MATLAB Engine. We also do not display any error messages to the user if MEX functions are used in MATLAB Engine code. I have submitted this feedback to our development organization in an enhancement request.

  2. You were able to use "mxGetClassName", a MEX function, in your MATLAB Engine code. Being able to do so contradicts the fact that MEX functions should not work in the MATLAB Engine. I have let development know that "mxGetClassName" can be used with the MATLAB Engine.

关于c++ - MATLAB mex API 与 MATLAB 引擎 API 之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34352964/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com