Fill a SAFEARRAY with BSTR values and print to console

I'm attempting to fill a SAFEARRAY of 10 BSTR with the value "test" and print out to console the value of each index of the SAFEARRAY after it has been assigned to verify correctness. I ran the debugger and got these values below (my SAFEARRAY is called sa). Somehow I am iterating the SAFEARRAY incorrectly or using the wrong types, each index should be "test". My ultimate goal is to create a DLL to inteface with MS excel but I am trying to get this right before I move on to that. Any advice on what im doing wrong?

sa[0] = "test"
sa[1] = "est"
sa[2] = "st"
sa[3] = "t"
sa[4] = ""
...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#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"t");
    }

    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;
}
Topic archived. No new replies allowed.