vc++基于com组件调用matlab m文件
void CVc2addDlg::OnButton1() {
// TODO: Add your control notification handler code here
UpdateData(TRUE); //更新,把输入框中的值更新到变量中
if(FAILED(CoInitialize(NULL))) //初始化调用com
{
AfxMessageBox("unable to initialize COM");
return;
}
// 得到 COM对象的 CLSID
CLSID CLSID_M4add;
HRESULT hr;
hr=CLSIDFromProgID(L"m3add.m4add",&CLSID_M4add);
//创建一个 COM对象的实例
IM4add* st=NULL;
hr=CoCreateInstance(CLSID_M4add, NULL,CLSCTX_ALL, IID_IM4add, (void** )&st);
//定义参数,与com件交互只能用VARIANT类型数据
VARIANT w1,b1,w2,b2,P,T,eg;
//初始化,一定要初始化不然报错
VariantInit(&w1);
VariantInit(&b1);
VariantInit(&w2);
VariantInit(&b2);
VariantInit(&P);
VariantInit(&T);
VariantInit(&eg);
P.vt=VT_R8|VT_ARRAY;
T.vt=VT_R8|VT_ARRAY;
eg.vt=VT_R8|VT_ARRAY;
w1.vt=VT_R8;
b1.vt=VT_R8;
w2.vt=VT_R8;
b2.vt=VT_R8;
SAFEARRAYBOUND rgsabound[2];
rgsabound[0].lLbound=0;
rgsabound[1].lLbound=0;
rgsabound[0].cElements=1;
rgsabound[1].cElements=2;
P.parray =SafeArrayCreate(VT_R8,2,rgsabound);
P.parray ->pvData =m_x;
SAFEARRAYBOUND rgsabound1[1];
rgsabound1[0].lLbound=0;
rgsabound1[0].cElements=1;
T.parray =SafeArrayCreate(VT_R8,1,rgsabound1);
T.parray ->pvData =m_y;
SAFEARRAYBOUND rgsabound2[1];
rgsabound2[0].lLbound=0;
rgsabound2[0].cElements=1;
eg.parray =SafeArrayCreate(VT_R8,1,rgsabound2);
eg.parray ->pvData =m_e;
//调用MATLAB中的函数
if (st!=NULL)
{//调用 COM 组件, 第一个参数为输出参数的个数,这里为4
//第二三四五个为输出的变量的地址,即&A,&B,&C,&D
//第六个、第七个为输入 COM的数据变量,即x,y ,e
LONG para =4;
st->msadd(para,&w1,&b1,&w2,&b2,P,T,eg);
memcpy(m_a,w1.parray->pvData,10*sizeof(double));
memcpy(m_b,b1.parray->pvData,5*sizeof(double));
memcpy(m_c,w2.parray->pvData,5*sizeof(double));
memcpy(m_d,b2.parray->pvData,sizeof(double));
st->Release();
}
else
{
AfxMessageBox("unsucceed");
}
CoUninitialize();//结束COM
UpdateData(FALSE);//把变量中的数据更新到窗体中。
}
m_x,m_y对应输入编辑框变量
m_a,m_b,m_c,m_d对应输出编辑框变量。
编辑错误:
Vc2addDlg.cpp
e:\vc++\vc2add\debug\m3add_1_0.tlh(51) : error C2146: syntax error : missing ';' before identifier 'MWFlags'
e:\vc++\vc2add\debug\m3add_1_0.tlh(51) : error C2501: 'IMWFlagsPtr' : missing storage-class or type specifiers
e:\vc++\vc2add\debug\m3add_1_0.tlh(51) : error C2501: 'MWFlags' : missing storage-class or type specifiers
e:\vc++\vc2add\debug\m3add_1_0.tlh(57) : error C2146: syntax error : missing ';' before identifier 'GetMWFlags'
e:\vc++\vc2add\debug\m3add_1_0.tlh(57) : error C2501: 'IMWFlagsPtr' : missing storage-class or type specifiers
e:\vc++\vc2add\debug\m3add_1_0.tli(14) : error C2143: syntax error : missing ';' before 'tag::id'
e:\vc++\vc2add\debug\m3add_1_0.tli(14) : error C2433: 'IMWFlagsPtr' : 'inline' not permitted on data declarations
e:\vc++\vc2add\debug\m3add_1_0.tli(14) : error C2501: 'IMWFlagsPtr' : missing storage-class or type specifiers
e:\vc++\vc2add\debug\m3add_1_0.tli(14) : fatal error C1004: unexpected end of file found
Error executing cl.exe.