本文参考了 http://blog.csdn.net/infocarrier/article/details/5854522
matlab中选择c++编译器 mex -setup
matlab函数
function [result] =matrix_multiply(A,B)
result = A*B;
end
采用这个编译
mcc -C -W cpplib:lib_matrix_multiply -T link:lib matrix_multiply.m (注意要用-C)
生产4个文件,lib_matrix_multiply.h lib_matrix_multiply.lib lib_matrix_multiply.dll lib_matrix_multiply.ctf
将4个文件拷贝到新建的一个vs2008 project中,然后采用下面的代码就ok了。
#include <iostream>
#include "mclmcrrt.h"
#include "lib_matrix_multiply.h"
#pragma comment(lib,"lib_matrix_multiply.lib")
#pragma comment(lib,"mclmcrrt.lib ")
using namespace std;
int main()
{
// 初始化MCR
if( !mclInitializeApplication(NULL,0) )
{
std::cout << "Could not initialize the application!" << std::endl;
return -1;
}
// 初始化引用
if( !lib_matrix_multiplyInitialize())
{
std::cout << "Could not initialize lib_matrix_multiply!" << std::endl;
return -1;
}
int a_rows = 100,a_cols = 200;
int b_rows = 200,b_cols = 300;
int c_rows = 100,c_cols = 300;
try
{
double *aData = new double[a_rows*a_cols];
// Initilization
for(int i=0;i<a_rows*a_cols;i++)
{
aData[i] = 1;
}
// Initilization
double *bData = new double[b_rows*b_cols];
for(int i=0;i<b_rows*b_cols;i++)
{
bData[i] = 2;
}
// Initilization
double *cData = new double[c_rows*c_cols];
for(int i=0;i<c_rows*c_cols;i++)
{
cData[i] = 0;
}
// // set the adata
//for(int i=0;i<a_rows;i++)
// {
// for(int j=0;j<a_cols;j++)
// {
// aData[i+j*a_rows] = 1; // In Matlab, it expanses according to the cols
// }
// }
//初始化 a
mwArray a(a_rows, a_cols, mxDOUBLE_CLASS);
a.SetData(aData, a_rows*a_cols); // set the data for a
//初始化 b
mwArray b(b_rows, b_cols, mxDOUBLE_CLASS); // b is the same with matlab which has the strat point at (1,1) sgliu
for(int i=1;i<b_rows+1;i++)
{
for(int j=1;j<b_cols+1;j++)
{
b(i,j) = 2;
}
}
b.GetData(bData, b_rows*b_cols); // get the data from b
//定义输出 c
mwArray c(c_rows, c_cols, mxDOUBLE_CLASS);
// 调用dll
matrix_multiply(1,c,a,b); // This is important 1 is the number of output parameters
// 拷贝数据到 C++
c.GetData(cData, c_rows*c_cols);
// 输出结果
for(int i=0;i<c_rows;i++)
{
for(int j=0;j<c_cols;j++)
{
cout<<cData[i+j*c_rows]<<" "; // In Matlab, it expanses according to the cols
}
cout<<endl;
}
// 释放内存
delete [] aData;
delete [] bData;
delete [] cData;
}
catch( const mwException& e)
{
std::cerr << e.what() << std::endl;
}
// 结束 lib
lib_matrix_multiplyTerminate();
// terminate MCR
mclTerminateApplication();
return 0;
}