VB向VC++的COM中传递数组的问题
//VB向COM传递数组
//这段代码的意思是,传进来的数组元素是BSTR类型的,得到每个元素,组成一个新的BSTR串,在返回给SetArr方法
STDMETHODIMP CArr::SetArr(VARIANT *pIn, VARIANT *pRet){ AFX_MANAGE_STATE(AfxGetStaticModuleState()) SAFEARRAY *psa=*(pIn->pparray);//获取从外部传递进来的数组,要用pparray,区别在于此 CComBSTR tmp; long lBound,uBound; SafeArrayGetLBound(psa,1,&lBound); SafeArrayGetUBound(psa,1,&uBound); for(long i=lBound;i<=uBound;i++) { VARIANT var; SafeArrayGetElement(psa,&i,&var); if(tmp.Length()==0)tmp.AppendBSTR(var.bstrVal); else { tmp.AppendBSTR(SysAllocString(L",")); tmp.AppendBSTR(var.bstrVal); } } pRet->vt=VT_BSTR; pRet->bstrVal=tmp.Copy(); return S_OK;}
Private Sub Command1_Click()Set obj = CreateObject("TestVar.Arr")Dim arr(0 To 3) As Stringarr(0) = CStr("aaa")arr(1) = CStr("bbb")arr(2) = CStr("ccc")Dim var As Variant'var = obj.SetArr(arr)'var = obj.SetArr(VarPtr(arr(0)))var = obj.SetArr(arr(0))MsgBox CStr(var)End Sub
Private Sub Command1_Click() Dim obj Set obj = CreateObject("TestCom.Test") Dim arr(0 To 3) As Variant arr(0) = "aaa" arr(1) = "bbb" arr(2) = "ccc" Dim var As Variant var = obj.SetArr(arr) 'var = obj.SetArr(VarPtr(arr(0))) 'var = obj.SetArr(arr(0)) MsgBox CStr(var)End Sub
[解决办法]
Dim arr() As StringRedim arr(0 to 2)arr(0) = CStr("aaa")arr(1) = CStr("bbb")arr(2) = CStr("ccc")Dim var As Variantvar = obj.SetArr(arr)