本就就针对网上到处流行的以“Matlab与C/C++混合编程”为题的例子进行调试。
此例已调试成功,代码如下:
#pragma comment( lib, "libmx.lib" )
#pragma comment( lib, "libmex.lib" )
#pragma comment( lib, "libeng.lib" )
#include<windows.h>
#include "engine.h"
#include<iostream>
using namespace std;
int PASCAL WinMain (HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpszCmdLine,
int nCmdShow)
{
Engine *ep;
mxArray *P=NULL,*r=NULL;
char buffer[301];
double poly[4]={1,0,-2,5};//表示1*x^3+0*x^2-2*x+5
if (!(ep=engOpen(NULL)))
{
fprintf(stderr,"\nCan't start MATLAB engine\n");
return -1;
}
P=mxCreateDoubleMatrix(1,4,mxREAL);
//mxSetClassName(P,"p");
memcpy((char *)mxGetPr(P),(char *)poly, 4*sizeof(double));
engPutVariable(ep,"p",P);
engOutputBuffer(ep,buffer,300);
engEvalString(ep,"disp(['多项式',poly2str(p,'x'),'的根']),r=roots(p)");
MessageBox(NULL,buffer,"example2 展示MATLAB 引擎的应用",MB_OK);
engClose(ep);
mxDestroyArray(P);
return 1;
}
------------------------------------------------------------------------
结果如图:
==============================================
注意事项:
1)加入#pragma comment( lib, "libmx.lib")等
2)WinMain函数一个字母都不能错int PASCAL WinMain (HINSTANCE hInstance,HINSTANCE hPrevInstance,LPSTR lpszCmdLine,int nCmdShow)
3)engPutVariable(ep,"p",P);其他版本少了中间那个小p
4)其他注意见【MATLAB与C的混合编程】之【C程序调用Matlab计算引擎】(1)和【MATLAB与C的混合编程】之【C程序调用Matlab计算引擎】(2)