Domanda

char cmd[40];
driver = FuncGetDrive(driver);
sprintf_s(cmd, "%c:\\test.exe", driver);

Non è possibile utilizzare cmd in

sei.lpFile = cmad;

così, come convertire gamma char di serie wchar_t?

È stato utile?

Soluzione

MSDN :

#include <iostream>
#include <stdlib.h>
#include <string>

using namespace std;
using namespace System;

int main()
{
    char *orig = "Hello, World!";
    cout << orig << " (char *)" << endl;

    // Convert to a wchar_t*
    size_t origsize = strlen(orig) + 1;
    const size_t newsize = 100;
    size_t convertedChars = 0;
    wchar_t wcstring[newsize];
    mbstowcs_s(&convertedChars, wcstring, origsize, orig, _TRUNCATE);
    wcscat_s(wcstring, L" (wchar_t *)");
    wcout << wcstring << endl;
}

Altri suggerimenti

Basta usare questo:

static wchar_t* charToWChar(const char* text)
{
    const size_t size = strlen(text) + 1;
    wchar_t* wText = new wchar_t[size];
    mbstowcs(wText, text, size);
    return wText;
}

Non dimenticare di chiamare delete [] wCharPtr sul risultato di ritorno quando hai finito, altrimenti si tratta di una perdita di memoria in attesa di accadere se continui a chiamare questo senza pulizia. Oppure utilizzare un puntatore intelligente come il commentatore di seguito suggerisce.

In alternativa, utilizzare stringhe standard, come nel seguente modo:

#include <cstdlib>
#include <cstring>
#include <string>

static std::wstring charToWString(const char* text)
{
    const size_t size = std::strlen(text);
    std::wstring wstr;
    if (size > 0) {
        wstr.resize(size);
        std::mbstowcs(&wstr[0], text, size);
    }
    return wstr;
}

Questo link ha esempi per molti tipi di conversioni di stringhe, compreso quello che ti interessa (look per mbstowcs_s)

Dal tuo esempio utilizzando swprintf_s lavoro sarebbe

wchar_t wcmd[40];
driver = FuncGetDrive(driver);
swprintf_s(wcmd, "%C:\\test.exe", driver);

Si noti la C in % C deve essere scritto con lettere maiuscole dal driver è un carattere normale e non un wchar_t.
Passando la stringa di swprintf_s (wcmd, "% S", cmd) dovrebbe funzionare anche

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top