我在 C# 中创建了一个 COM 包装器,其中包含一个返回字符串数组的方法:
public string[] GetArrayOfStrings()
{
string[] array = new string[3];
array[0] = "first";
array[1] = "second";
array[2] = "third";
return array;
}
在 VB6 中,我调用该方法并在列表中显示字符串,如下所示:
Dim s() As String
s = obj.GetArrayOfStrings()
For i = LBound(s) To UBound(s)
List1.AddItem s(i)
Next i
有谁知道如何从 Borland C++ 调用该方法并获取返回数组中的所有元素?
最佳答案
COM 中的数组由 SAFEARRAY
处理结构。
根据 COM 对象公开数组的方式,它可能会直接返回一个 SAFEARRAY
,例如:
SAFEARRAY *psa = obj->GetArrayOfStrings();
VARTYPE vtype;
SafeArrayGetVartype(psa, &vtype);
if (vtype == VT_BSTR)
{
LONG lBound, uBound;
SafeArrayGetLBound(psa, 0, &lBound);
SafeArrayGetUBound(psa, 0, &uBound);
for(LONG i = lBound; i <= uBound; ++i)
{
BSTR str;
SafeArrayGetElement(psa, &i, &str);
...
SysFreeString(str);
}
}
SafeArrayDestroy(psa);
或者它可能被包裹在 VARIANT
中改为结构,例如:
VARIANT v = obj->GetArrayOfStrings();
if (V_VT(&v) & VT_ARRAY)
{
SAFEARRAY *psa = V_ARRAY(&v);
...
}
VariantClear(&v);
无论哪种方式,数组中的元素都可以包含也可以不包含在 VARIANT
结构中,例如:
SafeArrayGetVartype(psa, &vtype);
if (vtype == VT_VARIANT)
{
...
VARIANT elem;
VariantInit(&elem);
SafeArrayGetElement(psa, &i, &elem);
...
VariantClear(&elem);
...
}
关于c++ - 如何在 Borland C++ 中调用返回字符串数组的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19151603/