Simsons
Simsons

Reputation: 12745

How to convert from CString to PCWSTR

I have the following method :

    VariantFromString(strXMLPath ,vXMLSource); 

and the signature of the method is:

HRESULT VariantFromString(PCWSTR wszValue, VARIANT &Variant);

Now while I am passing a CString as below:

char cCurrentPath[FILENAME_MAX];

        if (!GetCurrentDir(cCurrentPath, sizeof(cCurrentPath)))
            {
                return errno;
            }
CString strXMLPath = cCurrentPath;
strXMLPath += XMLFILE;
VariantFromString(strXMLPath ,vXMLSource);

I am getting the error: Can not Convert from CString to PCWSTR

Upvotes: 1

Views: 3780

Answers (1)

tenfour
tenfour

Reputation: 36896

You really should be using Unicode (wchar_t instead of char). That is how the OS operates internally, and would prevent having to constantly convert between char types like this.

But in this scenario, you could use CString::AllocSysString to convert it to a BSTR, which is compatible with PCWSTR. Just make sure it gets freed with SysFreeString.

[edit] For example, you could change your function to:

VARIANT VariantFromString(const CString& str)
{
    VARIANT ret;
    ret.vt = VT_BSTR;
    ret.bstrVal = str.AllocSysString();
    return ret;
}

Upvotes: 3

Related Questions