VC与Matlab混合编程之调用动态链接库dll——<二>
1、是先建立 matlab 的 m 文件。
ellipsefit.m
其包含:function [Xc,Yc,A,B,Phi,P]=ellipsefit(x,y)
2.MCC命令编译生成得到h、dll、lib等文件
在matlab命令行中输入:
mcc -W cpplib:ellipsefit ellipsefit.m -T link:lib (此方式为c++风格函数)
(具体命令含义可参考《精通matlab与C/C++混合程序设计》刘维,第3版,北京航空航天大学出版社。)
(ellipsefit是生成的lib文件名,可以随意命名。ellipsefit.m是想调用的.m文件名。
至此,可以发现在ellipsefit.m所在的目录生成了一系列文件。我们将要使用:ellipsefit.h, ellipsefit.dll, ellipsefit.lib
2.3:新建一个 VC 工程:test
为了简单,我们在这里建立一个win32控制台程序。如下:
然后,将上面这3个文件(ellipsefit.h, ellipsefit.dll, ellipsefit.lib
)拷贝到VC工程所在的目录中,以便VC调用之,并将.h文件加入到工程中。
其中,ellipsefit.h中的function [Xc,Yc,A,B,Phi,P]=ellipsefit(x,y)
对应的c++风格的函数接口是:
extern LIB_ellipsefit_CPP_API void MW_CALL_CONV ellipsefit(int nargout, mwArray& Xc, mwArray& Yc, mwArray& A, mwArray& B, mwArray& Phi, mwArray& P, const mwArray& x, const mwArray& y);
即在自己的主程序中调用该接口即可,c++中使用mwArray矩阵进行数据操作
2.3 VC 编程:(代码如下 )
// test.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include<vector>
#include<iostream>
#include<fstream>
/********************************
VC调ì??用??mcc产¨2生|¨2的ì?dll
************************************/
#include "mclmcrrt.h"
#include "mclmcr.h"
#include "mclcppclass.h"
#include "matrix.h"
// include lib head file
#include "ellipsefit.h"
// link matlab sys lib
#pragma comment(lib, "mclmcrrt.lib")
#pragma comment(lib, "libmx.lib")
#pragma comment(lib, "libmat.lib")
#pragma comment(lib, "mclmcr.lib")
// link lib
#pragma comment(lib, "ellipsefit.lib")
using namespace std;
bool readFile(vector<double> &vec_in, ifstream &infile)
{
double temp;
while(infile>>temp)
vec_in.push_back(temp);
return true;
}
bool ellipsefit_dll(double &Xc,double &Yc,double &A,double &B,double &Phi,double &P,vector<double> x,vector<double> y)
{
mwArray mwa_x(x.size(),1 , mxDOUBLE_CLASS), mwa_y(y.size(),1 , mxDOUBLE_CLASS);
mwa_x.SetData(&x[0],x.size());
mwa_y.SetData(&y[0],y.size());
mwArray mwa_Xc(1,1,mxDOUBLE_CLASS),mwa_Yc(1,1,mxDOUBLE_CLASS),mwa_A(1,1,mxDOUBLE_CLASS),mwa_B(1,1,mxDOUBLE_CLASS),
mwa_Phi(1,1,mxDOUBLE_CLASS),mwa_P(1,1,mxDOUBLE_CLASS);
ellipsefit(6,mwa_Xc,mwa_Yc,mwa_A,mwa_B,mwa_Phi,mwa_P,mwa_x, mwa_y);
Xc=mwa_Xc(1,1);
Yc=mwa_Yc(1,1);
A=mwa_A(1,1);
B=mwa_B(1,1);
Phi=mwa_Phi(1,1);
P=mwa_P(1,1);
return true;
}
int main(int argc, _TCHAR* argv[])
{
if (!mclInitializeApplication(NULL, 0))
{
cout << "Could not initialize the application."<< endl;;
}
if (!ellipsefitInitialize())
{
cout << "Can‘t Initalize!" << endl;
}
cout << "开a始o?运?行D" << endl;
ifstream infile_x,infile_y;
char *infile_name_x="x.txt";
char *infile_name_y="y.txt";
infile_x.open(infile_name_x);
vector<double> vec_x;
readFile(vec_x,infile_x);
infile_y.open(infile_name_y);
vector<double> vec_y;
readFile(vec_y,infile_y);
double Xc,Yc,A,B,Phi,P;
ellipsefit_dll(Xc,Yc,A,B,Phi,P,vec_x,vec_y);
cout<<"Xc="<<Xc<<endl;
cout<<"Yc="<<Yc<<endl;
cout<<"A="<<A<<endl;
cout<<"B="<<B<<endl;
cout<<"Phi="<<Phi<<endl;
cout<<"P="<<P<<endl;
ellipsefitTerminate();
mclTerminateApplication();
system("pause");
return 0;
}
时间: 2024-10-12 13:13:04