vendredi 4 janvier 2019

Inconsistent string/wchar content depending on code's location?

I'm having 3 different kind of results, depending on the free functions I'm using:

struct __declspec(dllexport) TimerPair final
{
    long long Time{};
    string Descr;
};

template<typename... T>
wchar_t* Message(T &&... args)
{
    wchar_t message[100];
    swprintf(message, 100, forward<T>(args)...);
    return message;
}

template<typename... T>
void LogMessage(T &&... args)
{
    Logger::WriteMessage(Message(forward<T>(args)...));
}

const wchar_t* ToWchar(string arg)
{
    std::wstring widestr = std::wstring(arg.begin(), arg.end());
    return widestr.c_str();
}

and the code in unit tests: (the o is a TimerPair structure)

// v1
LogMessage(L"%s : %.4fms\n", ToWchar(o.Descr), (float)o.Time / 1000000);

// v2
std::wstring widestr = std::wstring(o.Descr.begin(), o.Descr.end());
Logger::WriteMessage(Message(L"%s : %.4fms\n", widestr.c_str(), (float)o.Time / 1000000));

// v3
std::wstring widestr = std::wstring(o.Descr.begin(), o.Descr.end());
wchar_t message[100];
swprintf(message, 100, L"%s : %.4fms\n", widestr.c_str(), (float)o.Time / 1000000);
Logger::WriteMessage(message);

The Logger::WriteMessage comes from MSFT unit test framework (using namespace Microsoft::VisualStudio::CppUnitTestFramework;)

In the first two cases, I get results like the following:

enter image description here

instead of the expected (case 3):

enter image description here

It looks like there is a pointer problem, but the code looks correct, especially with the value argument (long long). What I am missing ?

Aucun commentaire:

Enregistrer un commentaire