【问题标题】:When creating a Matlab MEX function, do I place mexFunction in c++ header file or source file?创建 Matlab MEX 函数时,我是否将 mexFunction 放在 c++ 头文件或源文件中?
【发布时间】:2017-06-09 16:46:57
【问题描述】:

我正在使用 Matlab 的 mex 函数来运行一些 c++ 源文件。我有几个 .cpp 文件可以进行不同的转换。我想做一个头文件来调用这些 .cpp 文件。我在网上看到的所有示例(到目前为止)仅将 mex 与 .cpp 文件一起使用。我的问题是,我在哪里使用:

void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])

在标题中?源文件?如果它在头文件中,我是否将它放在一个类中?我对像这样将文件链接在一起有点陌生。

【问题讨论】:

  • 基本上没关系。只需将函数实现放在任何源文件中即可。类不是必需的。
  • 想想mexFunction,就像在标准程序中main一样。 matlab调用mex文件时,调用mexFunction

标签: c++ matlab mex


【解决方案1】:

我提供的示例来自一年前编写 Matlab 绑定时的 C 或 C++ 代码。 Mex 是 Matlab 可执行文件,它们是平台相关的,它们不兼容不同的平台和版本。

在源文件中添加mex.h。添加包含 MATLAB API 函数声明的 C 或 C++ 头文件 mex.h


示例代码:

/* This header is the must and its the main interface to talk with Matlab*/
#include "mex.h" 
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])     
{
    mexPrintf("howdyyyy!\n"); 
    return;
}

您可以在 matlab/extern/include 找到 MATLAB 的头文件。您也可以查看matrix.h 文件。

如果你使用 Matlab 编辑器,那么你可以这样做,下一步是编译。在Matlab控制台上,输入命​​令编译yourfile.cpp

$ mex yourfile.cpp

MEX 函数编译完成,你可以像任何 M 文件函数一样在 Matlab 中调用它,示例

输出。

$ yourfile
howdyyyy!

【讨论】:

  • 如果我有一堆函数要保存在单独的 .cpp 文件中,而另一个 .cpp 文件决定调用哪个文件?我希望用户输入要在 matlab 中使用的转换,并让 mex 代码决定使用哪个转换器(每个转换器都在他们自己的源文件中)。
  • @theNovice 你熟悉building libraries?
  • 为了使用 Matlab API,它需要引用 mex.h,您可以将头文件保留在头文件中并将其包含在您的 *.cpp 文件中,或者其他选项也可以,直到它会找到对 matlab API 的引用。
  • @LethalProgrammer 现在我有:convertAtoB.cpp 和 convertBtoC.cpp 都按照你说的做了。有自己的 mexFunction。我想做一个 'convert('A','C',other_inputs)' 调用 convertAtoB.cpp 和 convertBtoC.cpp 来得到答案。
  • @LethalProgrammer 我不熟悉构建库。我是否应该创建进行转换的函数(没有 mexFunction),将它们放入库中,并拥有一个使用它们的 mexxed 源文件?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多