0

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);
}
rahman
  • 4,820
  • 16
  • 52
  • 86

2 Answers2

1

"%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());
john
  • 85,011
  • 4
  • 57
  • 81
1

To convert wchar* to char*

const std::wstring wStr = /*your WCHAR* */;
const char* str = std::filesystem::path(wStr).string().c_str();
Eduard Rostomyan
  • 7,050
  • 2
  • 37
  • 76
  • I can compile only with c++11 for now. But really? Does it work with `filesystem`? What about size? I will try it anyway – rahman Dec 27 '22 at 14:44
  • Are you sure you want me to assign pointer to wstring? error: conversion from ‘WCHAR* {aka short unsigned int*}’ to non-scalar type ‘const wstring {aka const std::__cxx11::basic_string}’ requested const std::wstring wStr = wszStr; – rahman Dec 27 '22 at 14:57
  • 1
    @rahman - This conversion works from `wchar_t*` to `char*`, but not from `unsigned short*`. So you have **two** problems, one being that your "wide chars" are not wide chars... – BoP Dec 27 '22 at 15:00
  • @BoP right. But .. any solution to that? – rahman Dec 27 '22 at 21:49
  • @rahman you can use boost::filesystem if your compiler is limited to C++11 – Eduard Rostomyan Dec 28 '22 at 00:24