当需要在C++程序中调用Matlab写好的函数时,把Matlab函数编译成dll动态库是一种好方法。
测试环境: Windows 10, Matlab 2015b, Visual Studio 2012
具体的步骤为:
1、在Matlab中选择compiler:
在命令窗口输入
mex -setup
2、在matlab中选择builder:
在命令窗口输入
mbuild -setup
3、生成dll:
在命令窗口输入
mcc -W cpplib:dllname -T link:lib function.m -a dependfilepath
其中dllname是希望编译成的dll的名字, function.m为将要编译的matlab函数的名字, -a后边接function运行时需要依赖的文件所在的路径,路径会递归包含进去。
如果想看到编译过程中的详细信息,可以增加-v参数。
具体地,给出一个例子说明:
在Matlab的Editor中写入:
function [out] = myPlus(a, b)
out = a + b;
end
保存成文件myPlus.m,之后在Matlab控制台输入下边命令(这里我的max和mbuild已经配置好了,不用进行改动。):
>> mex -setup
MEX configured to use 'Microsoft Visual C++ 2012 (C)' for C language compilation.
Warning: The MATLAB C and Fortran API has changed to support MATLAB
variables with more than 2^32-1 elements. In the near future
you will be required to update your code to utilize the
new API. You can find more information about this at:
http://www.mathworks.com/help/matlab/matlab_external/upgrading-mex-files-to-use-64-bit-api.html.
To choose a different language, select one from the following:
mex -setup C++
mex -setup FORTRAN
>> mbuild -setup
MBUILD configured to use 'Microsoft Visual C++ 2012 (C)' for C language compilation.
To choose a different language, select one from the following:
mex -setup C++ -client MBUILD
mex -setup FORTRAN -client MBUILD
>> mcc -W cpplib:myPlus -T link:lib myPlus.m
使用 'Microsoft Visual C++ 2012' 编译。
>>
之后在同级目录中会产生一系列相应的文件,其中包括了.h、.cpp、.dll、.lib文件。
如果在实际中myPlus.m文件中需要调用其它的m文件,文件路径也不在当前路径的话,可以通过-a 命令把包含依赖的m文件的路径添加到后边(不需要引号)
下边为如何在C++中调用Matlab编译产生的dll库:
打开VS2012,新建控制台项目“dllTest”,然后将上边四个后缀名文件拷贝到项目路径下。
在 [解决方案资源管理器] 中,项目名字“dllTest”上右键选择 [属性],打开 [dllTest属性卡] ->[配置属性]->[VC++ 目录],之后编辑 [包含目录],添加路径"C:\Program Files\MATLAB\R2015b\extern\include"。
之后在 [dllTest属性卡] ->[配置属性]->[链接器]->[常规] 中的 [附加库目录] 中,编辑添加"C:\Program Files\MATLAB\R2015b\extern\lib\win64\microsoft",以及"D:\Users\DELL\Documents\MATLAB\dllTest"。其中"D:\Users\DELL\Documents\MATLAB\dllTest"为编译的dll所在目录。同时,在 [dllTest属性卡] ->[配置属性]->[链接器]->[输入] 中的 [附加依赖项] 中,编辑添加"mclmcr.lib","mclmcrrt.lib", "myPlus.lib"。
经过上边的配置之后,就可以编写调用dll库的C++程序了。
后续再继续整理如何在C++中调用Matlab编译的dll库方法。