我正在尝试用值“test”填充 BSTR 类型的 10 个索引的 SAFEARRAY,并在分配 SAFEARRAY 的每个索引以验证正确性后打印出来以控制台其值。我运行调试器并为前 5 个索引获得了以下这些值(我的 SAFEARRAY 称为 sa)。不知何故,我错误地迭代了 SAFEARRAY 或使用了错误的类型,每个索引都应该是“测试”。关于我做错了什么的任何建议?
sa[0] = "test"
sa[1] = "est"
sa[2] = "st"
sa[3] = "t"
sa[4] = ""
……
#include <iostream>
#include <string>
#include <Windows.h>
#include <atlbase.h>
#include <comutil.h>
#include <string.h>
#include <stdio.h>
using namespace std;
void fillVariant(VARIANT& varIn, BSTR &srcArray);
int main()
{
BSTR *theArray = new BSTR[10];
for(int i = 0 ; i < 10; i++)
{
theArray[i] = SysAllocString(L"test");
}
VARIANT variantArray;
fillVariant(variantArray, *theArray);
return 0;
}
void fillVariant(VARIANT& varIn, BSTR &srcArray)
{
VARIANT *variantArray = &varIn;
VariantInit(variantArray);
variantArray->vt = VT_ARRAY|VT_BSTR;
SAFEARRAY* sa;
SAFEARRAYBOUND aDim[1];
aDim[0].lLbound = 0;
aDim[0].cElements = 10;
sa = SafeArrayCreate(VT_BSTR, 1, aDim);
BSTR* dwArray = NULL;
SafeArrayAccessData(sa, (void**)&dwArray);
for(int i = 0; i < 10; i++)
{
dwArray[i] = &srcArray[i];
BSTR tmp = (BSTR) dwArray[i];
std::wstring ws(tmp);
//std::wstring ws(*dwArray[i], SysStringLen(dwArray[i]));
std::wcout << ws << endl;
}
SafeArrayUnaccessData(sa);
variantArray->parray = sa;
}