简体   繁体   中英

In C++, how do you initialize an array of pointers to wchar_t* (resulting in wchar_t**)?

I'm calling a COM function that requires a wchar_t** argument. What I would like to do is:

wchar_t* arr[3] = {L"str1", L"str2", L"str3"};

What I get back is a const wchar_t** , which the compiler rejects.

I also tried:

wchar_t* arr[3];
wchar_t p1[] = L"str1";
wchar_t p2[] = L"str2";
wchar_t p3[] = L"str3";
arr[0] = p1;
arr[1] = p2;
arr[2] = p3;

What I get back is wchar_t* (*)[3] , which the compiler also rejects.

I'm new to C++ and really struggling with how string literals are handled.

ETA: The function I'm trying to use is GetIDsOfNames and the second parameter is where I'm having a problem. I want to pass 3 names in that parameter (I can successfully pass one name with wchar_t ptName[] = L"namestring" but can't figure out how to combine multiple names in an array).

HRESULT GetIDsOfNames(  
REFIID   riid,  
LPOLESTR *rgszNames, 
UINT     cNames,  
LCID     lcid,  
DISPID   *rgDispId  
); 

The main problem you are encountering is that the array must be an array of pointers to non-constant characters, however you are trying to use string literals which are constant characters.

Most examples you find online of calling this function ignore this problem because the Microsoft compiler allowed this type error up until recently (and still does if you don't invoke it in strict standard mode, AFAIK).

To set up the array in Standard C++ the code could be:

wchar_t p1[] = L"str1";
wchar_t p2[] = L"str2";
wchar_t p3[] = L"str3";
wchar_t* arr[3] = { p1, p2, p3 };

and so the whole call might be:

DISPID dispid[3];
HRESULT result = iFoo->GetIDsOfNames( IID_NULL, arr, 3, LOCALE_SYSTEM_DEFAULT, dispid);

The code you described as "I also tried:" would be correct but I guess you mistakenly went on to put &arr as argument to GetIDsOfNames, instead of arr .

It's normal practice in COM programming for C++ to use wrapper classes that provide a more convenient C++ interface to these underlying C Win32 API functions .

A string literal is const data in C++. You can't assign a pointer-to-const to a pointer-to-non-const without using a typecast, eg:

const wchar_t* arr[3] =
{
    L"str1",
    L"str2",
    L"str3"
};

...->GetIDsOfNames(..., const_cast<LPOLESTR*>(arr), 3, ...);

Alternatively:

wchar_t* arr[3] =
{
    const_cast<wchar_t*>(L"str1"),
    const_cast<wchar_t*>(L"str2"),
    const_cast<wchar_t*>(L"str3")
};

...->GetIDsOfNames(..., arr, 3, ...);

Otherwise, you will have to make a copy of the const data into non-const arrays, like MM's answer shows.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM