Home > Back-end >  Converting SQLWCHAR * to char*
Converting SQLWCHAR * to char*

Time:12-28

Working for the first time in the area of unicode and widechars,

I am trying to convert WCHAR* to char*. (WCHAR typedefed to SQLWCHAR, and eventually to unsigned short)

And I need to support all platforms(windows, mac, linux).

What I have as input is a WCHAR* and its length. I figured, if I convert the input to wstring, I will have a chance to then strcpy/ strdup it to the output variable.

But looks like I am not constructing my wstring correctly because wprintf doesn't print its value.

Any hints what I am missing?

#include <iostream>
#include <codecvt>
#include <locale>
SQLRETURN SQL_API SQLExecDirectW(SQLHSTMT phstmt, SQLWCHAR* pwCmd, SQLINTEGER len)
{
   char *output;
   wchar_to_utf8(pwCmd, len, output);
   // further processing
   SQLRETURN rc;
   return rc;
}

int wchar_to_utf8(WCHAR *wStr, int size, char *output)
{
    std::wstring ws((const wchar_t*)wStr, size - 1);
    wprintf(L"wstring:%s\n", ws);
    std::wstring_convert<std::codecvt_utf8<wchar_t>> conv;
    std::string t = conv.to_bytes(ws);
    /*allocate output or use strdup*/
    strncpy(output, t.c_str(), size); // todo:take care of the last null char
    return strlen(output);
}

CodePudding user response:

"%s" in a wprintf format string requires a wchar_t* argument, so

wprintf(L"wstring%s\n", ws);

should be

wprintf(L"wstring%s\n", ws.c_str());

CodePudding user response:

To convert wchar* to char*

const std::wstring wStr = /*your WCHAR* */;
const char* str = std::filesystem::path(wStr).string().c_str();
  • Related