COM 中STDMETHODIMP CZStation::GetDStation(VARIANT vStaList)
{
SAFEARRAY* pArray=vStaList.parray; //vStaList是一个SAFEARRAY数组
}
vc里可以将SAFEARRAY转换成VARIANT,C#中GetDStation(object vStaList); 如何传入object?
下面是我的做法:
object[] dlist = new object[2];
dlist[0] = 10;
dlist[1] = 15;
object vstalsit = new System.Runtime.InteropServices.VariantWrapper(dlist);
zst.GetDStation(vstalsit);
但提示异常:VariantWrappers 不能存储在 Variant 中。
问题补充:
//完整的COM函数定义如下
STDMETHODIMP CZStation::GetDStation(VARIANT vStaList,DOUBLE* DStation)
{
SAFEARRAY* pArray=vStaList.parray;
long Low(0),High(0);
SafeArrayGetLBound(pArray,1,&Low);
SafeArrayGetUBound(pArray,1,&High);
LONG i;
DOUBLE pValue;
for(i=Low; i<High-Low+1; i=i+2)
{
SafeArrayGetElement(pArray, &i, &pValue);
*DStation+=pValue;
}
return S_OK;
}
VC++中调用成功:
CoInitialize(NULL);
double dsta;
SAFEARRAY* pSA;
SAFEARRAYBOUND aDim[1];
aDim[0].lLbound=0;
aDim[0].cElements=2;
pSA=SafeArrayCreate(VT_R8,1,aDim);
ASSERT(pSA);
long aLong[1];
aLong[0]=0;
DOUBLE vTmp;
vTmp=5;
SafeArrayPutElement(pSA,aLong,&vTmp);
aLong[0]=1;
vTmp=10;
SafeArrayPutElement(pSA,aLong,&vTmp);
VARIANT var;
VARTYPE vt;
VariantInit(&var);
SafeArrayGetVartype(pSA,&vt);
var.vt = VT_ARRAY|vt;
var.parray=pSA;
CLSID clsid;
CLSIDFromProgID(OLESTR("ZGISCOM.ZStation"),&clsid);
CComPtr<IZStation> pStation;
pStation.CoCreateInstance(clsid);
dsta = pStation->GetDStation(var);
pStation.Release();
CoUninitialize();
在C#中调用COM,
(1)
ZStation zst = new ZStationClass();
double dSta = 0;
double[] dlist = new double[2];
dlist[0] = 10.0;
dlist[1] = 15.0;
object vstalsit = new System.Runtime.InteropServices.VariantWrapper(dlist);
dSta = zst.GetDStation(vstalsit)://提示异常:VariantWrappers 不能存储在 Variant 中
(2)
object vstalsit = dlist;
dSta = zst.GetDStation(vstalsit)://直接报错
************************************************************************************************
终于把问题解决了,我用的是VS2005,在COM里使用SafeArrayGetElement(pArray, &i, &pValue);语句,用VC调用COM没有问题,但用C#调用就出