本篇笔记将纪录C++调用Matlab封装生成的动态库。
编译环境:VS2008 + Matlab2010a
一、Matlab编译生成dll
编写一个myadd.m文件,实现加法:
function [y,z]=myadd(a,b)
y = a+b;
z = a+2*b;
end
在Matlab的命令行中安装编译环境:
前后分别输入mex –setup和mbuild –setup,在Select a compiler:中选择VS2008即可。
在MATLAB命令框中输入以下命令:
mcc -W cpplib:libmyadd -T link:lib myadd.m
生成的过程可能需要一点时间。生成libmyadd.lib, libmyadd.h, libmyadd.dll 等文件。至此,动态库生成成功。
二、VS的设置
1.新建一个win32控制台应用程序用以测试。
2.将上述h、lib、dll文件拷贝至工程目录下。
3.设置工程属性:(你的matlab安装路径)
附加包含目录:D:\matlab\extern\include
附加库目录:D:\matlab\extern\lib\win32\microsoft
输入库文件:mclmcrrt.lib mclmcr.lib libmyadd.lib
4.设置系统环境变量:
在我的电脑->属性->高级选项->环境变量,在path中添加:
D:\matlab\bin\win32
D:\matlab\bin
5.编写调用代码:在main函数中添加如下测试代码:
#include <iostream>
#include "libmyadd.h"
int main()
{
if( !libmyaddInitialize())
{
std::cout << "Could not initialize libmyadd2!" << std::endl;
return -1;
}
try
{
// declare and initialize a
mwArray a(2, 2, mxDOUBLE_CLASS);
double *aData;
aData = new double[4];
int i;
for( i=0; i<4; ++i)
{
aData[i] = 1.0*i;
}
// print output
std::cout << "a = " << std::endl;
std::cout << aData[0] << ",\t" << aData[1] << std::endl;
std::cout << aData[2] << ",\t" << aData[3] << std::endl;
a.SetData(aData, 4);
// declare and initialize b
mwArray b(2, 2, mxDOUBLE_CLASS);
b(1,1) = 11.;
b(1,2) = 12.;
b(2,1) = 21.;
b(2,2) = 22.;
mwArray y(2, 2, mxDOUBLE_CLASS);
mwArray z(2, 2, mxDOUBLE_CLASS);
// call the function
myadd(2, y, z, a, b);
// copy data from mwArray to C++ objects
// allocate outputs
double *yData, *zData;
yData = new double[4];
if( yData == NULL )
{
std::cout << "Failed to allocate memory for yData!" << std::endl;
return -1;
}
zData = new double[4];
if( zData == NULL )
{
std::cout << "Failed to allocate memory for zData!" << std::endl;
return -1;
}
// copy data from mwArray to C++
y.GetData(yData, 4);
z.GetData(zData, 4);
// print output
std::cout << "y = " << std::endl;
std::cout << yData[0] << ",\t" << yData[1] << std::endl;
std::cout << yData[2] << ",\t" << yData[3] << std::endl;
std::cout << "z = " << std::endl;
std::cout << zData[0] << ",\t" << zData[1] << std::endl;
std::cout << zData[2] << ",\t" << zData[3] << std::endl;
// deallocate memory
delete [] aData;
delete [] zData;
delete [] yData;
}
catch( const mwException& e)
{
std::cerr << e.what() << std::endl;
}
// terminate the lib
libmyaddTerminate();
// terminate MCR
mclTerminateApplication();
return 0;
}
6.运行结果
三、其他方法
如果你想摆脱matlab,写自己的C++语言来实现matlab的功能。其实原理很简单,只是需要很了解matlab的函数功能。我在CSDN中找到了matlab2c的库和相关代码,简直太赞了,分享给大家:
https://blog.csdn.net/luanpeng825485697/article/details/77510987