VC.net 字符串到 LPWSTR [英] VC.net String to LPWSTR
问题描述
如何将字符串转换为 LPWSTR
How can I transform from string to LPWSTR
String^ str= "hello world";
LPWSTR apppath= (LPWSTR)(Marshal::StringToHGlobalAnsi(str).ToPointer());
但它不起作用.转换后:
But it doesn't work.After transformed:
推荐答案
您正在尝试将单字节字符(这就是 Marshal::StringToHGlobalAnsi
返回的内容)读取为宽字符(这就是LPWSTR
类型指向),并且您将内存中的任何内容解释为宽字符串.
You're trying to read single-byte characters (that's what Marshal::StringToHGlobalAnsi
is returning) as wide characters (that's what an LPWSTR
type points to), and you're getting whatever is in memory interpreted as a wide-character string.
你需要编组合适的类型,并且你需要知道结果的生命周期.这是一个示例程序,它显示了一种方法,从 marshal_context 中的 MSDN 示例修改而来::marshal_as:
You need to marshal the appropriate type, and you need to be aware of the lifetime of the result. Here's an example program that shows one way to do it, modified from the MSDN example in marshal_context::marshal_as:
// compile with: /clr
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <msclr\marshal.h>
using namespace System;
using namespace msclr::interop;
int main() {
marshal_context^ context = gcnew marshal_context();
String^ str = "hello world";
LPWSTR apppath = const_cast<wchar_t*>(context->marshal_as<const wchar_t*>(str));
wprintf(L"%s\n", apppath);
delete context;
return 0;
}
请注意,删除 context
后,对 apppath
的引用很可能是伪造的.
Note that a reference to apppath
is likely to be bogus after the deletion of context
.
这篇关于VC.net 字符串到 LPWSTR的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!