它必须是您未显示的代码部分中的某些内容。这对我有用:
C#类:
[ComVisible(true)]
[Guid("BE55747F-FEA9-4C1F-A103-32A00B162DF0")]
[ClassInterface(ClassInterfaceType.AutoDual)]
public class Test
{
//[return: MarshalAs(UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_BSTR)]
public string[] GetStringArray()
{
var a = new string[3];
a[0] = "string0";
a[1] = null;
a[2] = "string2";
return a;
}
public string[] GetStringArray2()
{
return null;
}
}
从 C++调用GetStringArray
和:GetStringArray2
SAFEARRAY* pSA = NULL;
testObject->GetStringArray(&pSA);
printf("str0: %ls\n", ((BSTR*)(pSA->pvData))[0]);
printf("ptr1: %x\n", ((BSTR*)(pSA->pvData))[1]);
printf("str2: %ls\n", ((BSTR*)(pSA->pvData))[2]);
SAFEARRAY* pSA2 = NULL;
testObject->GetStringArray2(&pSA2);
printf("pSA2: %x\n", pSA2);
跑:
str0: string0
ptr1: 0
str2: string2
pSA2: 0
我不必指定如何编组数组(注释掉的行),因为SAFEARRAY(VT_BSTR)
默认情况下它会被编组。
编辑:我想我知道问题出在哪里。您正在使用 ATL CComSafeArray
,它不期望NULL
SAFEARRAY 的设计:
CComSafeArray(_In_ const SAFEARRAY *psaSrc) : m_psa(NULL)
{
ATLASSERT(psaSrc != NULL);
HRESULT hRes = CopyFrom(psaSrc);
if (FAILED(hRes))
AtlThrow(hRes);
}
您应该像这样更改代码:
CComSafeArray<BSTR> itemEntities;
SAFEARRAY* pItemEntities = objController1->ListItems(sPath);
if (NULL != pItemEntities)
itemEntities.Attach(pItemEntities);
或者,直接分配m_psa
:
CComSafeArray<BSTR> itemEntities
itemEntities.m_psa = objController1->ListItems(sPath);
if (!itemEntities)
{
// NULL returned
}