编写可从 MATLAB(MEX 文件)调用的 C++ 函数
创建用现代 C++ 实现并可以从 MATLAB® 中调用的高性能函数
使用 C++ MEX API 创建具有以下特性的 MATLAB 函数:提供 C++ 程序的效率并且能够从 MATLAB 访问外部函数和库。C++ MEX API 提供以下功能:
使用现代 C++ 编程功能和面向对象的设计。
从 MEX 函数中调用 MATLAB 函数。
无缝集成到 MATLAB 中,从 MATLAB 获取输入并向其返回结果。
支持 MATLAB 数据类型和写入时复制 (copy-on-write) 语义。
编写线程安全的多线程 MEX 函数。
在进程外执行 C++ MEX 函数。
注意
MATLAB C++ API 中的函数使用 MATLAB Data API for C++ 中定义的 matlab::data::Array
类。如果您的 MEX 函数必须在 MATLAB R2017b 或更早版本中运行,或者您更喜欢使用 C 语言,则请改用 C Matrix API,它可用于 mxArray
数据结构。有关详细信息,请参阅编写可从 MATLAB(MEX 文件)调用的 C 函数。
主题
创建 C++ MEX 函数
- C++ MEX 函数
MEX 文件可实现用 C++ 语言编写的 MATLAB 函数。 - 创建 C++ MEX 源文件
如何创建基本的 C++ MEX 函数。
设置和编译 MEX 文件
- 编译 C++ MEX 程序
在不同平台上编译 MEX 应用程序。 - Test Your Build Environment
Test your build environment with a predefined C++ MEX file. - C++ MEX API
使用 C++11 功能和 C++ Engine API 来实现 MEX 函数。
C++ MEX 函数的设计
- Structure of C++ MEX Function
Implement a class that overrides the function call operator()
to create a functor object. - Avoid Copies of Arrays in MEX Functions
Techniques to avoid making copies of large arrays to reduce memory usage and improve execution speed. - Managing External Resources from MEX Functions
Customize theMexFunction
class to better handle the resources used by your MEX function. - Handling Inputs and Outputs
Check the size and type of inputs and display error messages in MATLAB. - 在 MATLAB 命令行窗口中显示输出
MEX 函数可以在 MATLAB 命令行窗口中显示输出。但是,有些编译器不支持在 MEX 函数中使用std::cout
。另一种方法是使用std::ostringstream
和 MATLABfprintf
函数在 MATLAB 命令行窗口中显示文本。 - Making async Requests Using mexCallMATLAB
Behavior when calling back into MATLAB with anasync
request likematlab::engine::MATLABEngine::fevalAsync
.
MEX 函数中的 MATLAB 数据类型
- Data Access in Typed, Cell, and Structure Arrays
Cell and structure arrays let you write to array contents without copying entire array. - Data Types for Passing MEX Function Data
Define the correct data types to pass data between MATLAB and MEX functions.
调用 MATLAB 函数
- Call MATLAB Functions from MEX Functions
Call MATLAB functions, passing arguments from and returning arguments to a MEX function. - Catch Exceptions in MEX Function
Catch exceptions thrown in a MEX function. - Execute MATLAB Statements from MEX Function
Execute MATLAB statements to create variables in the caller's workspace.
单独的线程和进程
- Call MATLAB from Separate Threads in MEX Function
MEX functions can call MATLAB from user-created threads using the C++ Engine asynchronous API. - Out-of-Process Execution of C++ MEX Functions
Execute C++ MEX functions in processes that are separate from the MATLAB process.
访问 MATLAB 变量
- Set and Get MATLAB Variables from MEX
Put variables into or get variables from the MATLAB base and global workspaces. - MATLAB Objects in MEX Functions
Pass MATLAB objects to MEX functions. - Using MEX Functions for MATLAB Class Methods
You can use MEX functions to implement methods for MATLAB classes.