VC.net String to LPWSTR

我与影子孤独终老i 提交于 2020-01-17 06:16:08

问题


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:


回答1:


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.

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;
}

Note that a reference to apppath is likely to be bogus after the deletion of context.



来源:https://stackoverflow.com/questions/22040707/vc-net-string-to-lpwstr

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!