本文主要介绍了如何用matlab的mcc命令生成dll,然后再Visual Studio加载调用生成的dll。
1). 打开matlab,新建m function,命名为testaddforcpp.m。这里我们简单写一个加法函数。代码后附。
2). matlab中配置编译器。这里我们选择Visual Studio的C/C++编译器。
3). 在matlab命令行输入mcc -l testaddforcpp.m,生成testaddforcpp.c,testaddforcpp.h, testaddforcpp.lib,testaddforcpp.dll等文件,这里我们主要用到后三个文件(.h .lib .dll)。
4). 打开Visual Studio 2005,建立一个Win32 Project,项目名为test_matlab_4
5). 然后打开tool -> option -> Projects and Solutions -> VC++ Directories -> Include files 增加matlab头文件目录地址。"C:\Program Files\MATLAB\R2009b\extern\include"。由于最近经常使用matlab,就把头文件目录添加到VC设置中。如果只是偶尔使用matlab,可以把头文件目录加到project -> test_matlab_4 properties -> C++ -> General -> Additional Include Directories 中。(这里我们借用以前日志的图片。)
6). 然后打开tool -> option -> Projects and Solutions -> VC++ Directories -> Library files 增加matlab库文件目录地址。"C:\Program Files\MATLAB\R2009b\extern\lib\win32\microsoft"。如果只是偶尔使用matlab,可以把库文件目录加到project -> test_matlab_4 properties -> Linker -> General -> Additional Library Directories 中。(这里我们借用以前日志的图片。)
7). 把头文件testaddforcpp.h添加到test_matlab_4中。test_matlab_4.cpp代码后附。
8). 在Configuration Properties -> Linker -> General -> Additional Library Directories中添加C:\Documents and Settings\DKim\My Documents\MATLAB\MATLAB_C_CPP,这是包含testaddforcpp.lib的路径。
9). 在Configuration Properties -> Linker -> Input -> Additional Dependencies中添加mclmcrrt.lib,testaddforcpp.lib。
10). 编译,链接,生成test_matlab_4.exe文件。注意记得把testaddforcpp.dll放到生成的test_matlab_4.exe的文件夹中。否则exe文件找不到并且无法调用dll。
源代码附下:
testaddforcpp.m文件
function result = testaddforcpp(v1, v2)
result = v1 + v2;
test_matlab_4.cpp文件
#include "stdafx.h"
#include "testaddforcpp.h"
#include <iostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
if( !mclInitializeApplication
(NULL,0))
{
cout << "Could not initialize the application." << endl;
return 1;
}
if( !testaddforcppInitialize())
{
cout << "Could not initialize the function library." << endl;
return 1;
}
mxArray *result;
mxArray *arguments[2];
arguments[0] = mxCreateDoubleScalar(2.0);
arguments[1] = mxCreateDoubleScalar(3.0);
mlxTestaddforcpp(1, &result, 2, arguments);
double *output = mxGetPr(result);
cout << "result is " << *output << endl;
mxDestroyArray(result);
mxDestroyArray(arguments[0]);
mxDestroyArray(arguments[1]);
testaddforcppTerminate();
mclTerminateApplication();
return 0;
}
源代码附下:
testaddforcpp.m文件
function result = testaddforcpp(v1, v2)
result = v1 + v2;
test_matlab_4.cpp文件
#include "stdafx.h"
#include "testaddforcpp.h"
#include <iostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
}