简体   繁体   中英

Convert std::basic_string<Char> to string

While MediaInfoDLL returns metadata (Sampling Rate, Channels, Stream Size, Title...) in std::basic_string<Char> format, I need to convert to string to be able to process it later. For example mi.Get(Stream_Audio, 0, __T("Performer")) returns "Artist Name" in std::basic_string<Char> format.

Can you help me?

Thank you in advance

Reading through the MediaInfoLib library's C++ code, it seems there are two possibilities. The library defines a type alias String , and this is the type you're seeing.

First, here is the definition of the Char and String types:

namespace MediaInfoLib {

/* ... */

//Char types
#undef  __T
#define __T(__x)     __T(__x)
#if defined(UNICODE) || defined (_UNICODE)
    typedef wchar_t Char;                    ///< Unicode/Ansi independant char
    #undef  __T
    #define __T(__x) L ## __x
#else
    typedef char Char;                       ///< Unicode/Ansi independant char
    #undef  __T
    #define __T(__x) __x
#endif

typedef std::basic_string<MediaInfoLib::Char> String;  ///< Unicode/Ansi independant string

/* ... */

}  // end namespace

If the macro UNICODE or _UNICODE was defined when the library was built, then the type is std::basic_string<wchar_t> , which is std::wstring in the standard library .

To convert this to std::string , please see this question: How to convert wstring into string?

The simplest answer there uses std::wstring_convert .

If the macro UNICODE or _UNICODE was NOT defined when the library was built, then MediaInfoLib::Char is the type char , and the MediaInfoLib::String type is std::basic_string<char> is already std::string . That is, in this case, the return type is already std::string .

Convert std::basic_string<Char> to string ... Yes, this is builtin type char

If Char is an alias of char , then std::basic_string<Char> is already std::string . No conversion is needed, since it is the same type.

MediaInfo has ZenLib as a dependency, which in turn has its own Ztring . You can do something like this:

#include "ZenLib/Ztring.h"
MediaInfoLib::String mediainfoString = mi.Get(Stream_Audio, 0, __T("Performer"));
ZenLib::Ztring zenlibZtring(mediainfoString);
std::string stdString = zenlibZtring.To_UTF8(); // or To_Local()

You can be slightly more efficient by directly using Ztring and skipping the intermediary mediainfoString .

ps std::wstring_convert() was deprecated in c++17 and should probably not be used.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM