您的位置:首页 > 博客中心 > 编程语言 >

实战c++中的string系列--string到LPCWSTR的转换

时间:2022-03-26 00:42

今天再来介绍一下如何从string到LPCWSTR的转换。

LPCWSTR是什么类型呢?
看看如何定义的:

typedef const wchar_t* LPCWSTR;

顾名思义就是:
LPCWSTR是一个指向unicode编码字符串的32位指针,所指向字符串是wchar型,而不是char型。

比如说MessageBoxW的第二、第三个参数就是LPCWSTR类型。

`MessageBoxW(__in_opt HWND hWnd, __in_opt LPCWSTR lpText,
            __in_opt LPCWSTR lpCaption, __in UINT uType)`

所以问题来了,有一个string类型的字符串,如何通过MessageBoxW进行显示呢?这就需要string到LPCWSTR类型的转换了!!

        string image_path = "c:\\avi.png";
        size_t size = image_path.length();
        wchar_t *buffer = new wchar_t[size + 1];
        MultiByteToWideChar(CP_ACP, 0, response->image_path.c_str(), size, buffer, size * sizeof(wchar_t));
        buffer[size] = 0;  //确保以 ‘\0‘ 结尾 
        ::MessageBox(NULL, buffer, NULL, NULL);
        delete buffer;
        buffer = null;

看到了吧 又一次用了MultiByteToWideChar函数。所以牢记这个函数的用法。

本类排行

今日推荐

热门手游