如何将Wchar_T转换为Lpwstr [英] How Do I Convert Wchar_T To Lpwstr

查看:610
本文介绍了如何将Wchar_T转换为Lpwstr的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我的代码片段如下所示。



Hi,
My code snippet looks like this.

typedef char* PSTRING;

LPWSTR   usri1_name;
wchar_t  ws[100];

PSTRING createUserVar = NULL;

/*"createUserVar"  is assigned with some value*/
/*Converting PSTRING to wchar_t */
swprintf(ws, 100, L"%hs", createUserVar);





现在我需要为usri1_name分配ws值,但我没有得到如何转换它。

请让我知道你对此的建议。



不同的方式也欢迎。



代码是写在c



Now i need to assign ws value to usri1_name but i am not getting how to convert it.
Please let me know your suggestion on this.

different ways of doing this also welcomed.

code is written in c

推荐答案

不需要转换。 LPWSTR 是指向宽字符串的指针, ws 是一个宽字符数组。所以你可以写:

There is no need for a conversion. LPWSTR is a pointer to a wide string and ws is an array of wide characters. So you can just write:
usri1_name = ws;



但是你必须要注意内存指向通过 usri1_name 。当 ws 超出范围时(例如,当离开函数或块时, ws 被定义),指针将变为无效。然后你必须使用 new malloc usri1_name ,将 ws 的内容复制到其中,并在不再需要时释放内存。


But you must take care of the memory pointed to by usri1_name. The pointer will become invalid when ws goes out of scope (e.g. when leaving the function or block where ws is defined). Then you must allocate memory on the heap using new or malloc for usri1_name, copy the content of ws into it, and release the memory when no longer needed.


因为WCHAR实际上是wchar_t和LPCWSTR实际上是wchar_t const *,你可以做的很简单:



As WCHAR is actually wchar_t and LPCWSTR is actually wchar_t const*, you can do simple:

usri1_name = ws;


我认为这两个答案都错过了重要的一点,那就是 必须 确保你想要的最后一个字符后面的字符成为字符串的一部分必须是 NULL 0x00 )。否则,当您的代码搜索字符串的结尾时,您将冒着缓冲区溢出的风险,并在100字符数组的末尾运行。
I think both of the answers miss an important point, which is that you must ensure that the character following the last character that you want to be part of the string must be NULL (0x00). Otherwise, you risk a buffer overrun when your code searches for the end of the string, and runs off the end of your 100 character array.


这篇关于如何将Wchar_T转换为Lpwstr的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆