在COM方法中用VARIANT类型传递数组数据
在COM方法中可用VARIANT类型传递数组数据,在VC++中用SAFEARRAY处理。下面给出输入和输出数组的例子
1。输入数组到COM中
STDMETHODIMP CTestCom1::vb2vc(VARIANT buffer)
{
long dim=SafeArrayGetDim(buffer.parray);
long ubound;
long lbound;
SafeArrayGetUBound(buffer.parray,dim,&ubound);
SafeArrayGetLBound(buffer.parray,dim,&lbound);
BSTR* buf;
BSTR pd[2];
SafeArrayAccessData(buffer.parray,(void**)&buf);
for (int i=lbound;i <ubound;i++)
pd[i]=buf[i];
}
return S_OK;
}
buffer为一维数组,存放字符串,在vb中的代码为
Dim oo As ARRAYTESTLib.TestCom1
Set oo = New ARRAYTESTLib.TestCom1
Dim buf(2) As String
buf(0) = "65 "
buf(1) = "anss "
oo.vb2vc buf
2。COM返回数组数据到vb
STDMETHODIMP CTestCom1::retarray(VARIANT *buffer)
{
//返回数组
SAFEARRAY FAR* psa;
SAFEARRAYBOUND rgsabound[1];
rgsabound[0].lLbound=0;
rgsabound[0].cElements=2;
psa=SafeArrayCreate(VT_I4,1,rgsabound);
long idx;
long setdt;
idx=0;
setdt=12;
SafeArrayPutElement(psa,&idx,&setdt);
idx=1;
setdt=342;
SafeArrayPutElement(psa,&idx,&setdt);
V_VT(buffer) = VT_ARRAY | VT_I4;
V_ARRAY(buffer)=psa;
return S_OK;
}
vb中的代码为:
Dim oo As ARRAYTESTLib.TestCom1
Set oo = New ARRAYTESTLib.TestCom1
Dim rarr As Variant
oo.retarray rarr
MsgBox rarr(0) & rarr(1)