开发者

System::String to QString

I'm calling a c++ lib and am writing a managed C++ wrapper class around the lib. The methods take parameters of QString and sometimes references to QString so that the value can be filled in. I have tried to use std::string and it appears to be fine until I compile it and link it to c# it's like the method declarations don't exist. So now I am trying to pass in System::String but I can't figure out how to convert that to QString. So an answer to this question can come in one of 2 forms. 1. Why can't I referenc开发者_运维问答e methods in c# to a managed c++ code having std::string parameters? Or, how do I convert a System::String to a QString?


Why can't I reference methods in c# to a managed c++ code having std::string parameters?

Only POD types may be automatically marshaled back and forth between native and managed code. std::string is not a POD type.

Or, how do I convert a System::String to a QString?

#include <string>
#include <QString>
#include <msclr/marshal_cppstd.h>

QString SystemStringToQString(System::String^ str)
{
    using namespace msclr::interop;
    return QString::fromStdWString(marshal_as<std::wstring>(str));
}

EDIT (in response to the comments on answer #6205169):

Proposed memory leak fix:

std::wstring MarshalString(String^ s)
{
    using namespace System::Runtime::InteropServices;
    std::wstring ret;
    IntPtr p = Marshal::StringToHGlobalUni(s);
    if (p.ToPointer())
    {
        ret.assign((wchar_t const*)p.ToPointer());
        Marshal::FreeHGlobal(p);
    }
    return ret;
}

Performance-wise, this is far less efficient than it could be, but it should work and shouldn't leak.


See this:

http://www.codeguru.com/forum/showthread.php?t=372298

It should get you down to a char* which is easily convertible to QString.


Well I am half way there. I just need to know if these methods create a memory leak and what I can do about it

I created a few helper methods to do this. I needed to do this to move from an old Qt library to CLI String. I can not update the Qt library as I do not have any control over that part of the code.

void MarshalString (  String ^ s, wstring& os ) {
    using namespace Runtime::InteropServices;
    const wchar_t* char = 
        (const wchar_t*)(Marshal::StringToHGlobalUni(s)).ToPointer();
    os = char;
}
QString SystemStringToQt( System::String^ str)
{
    wstring t;
    MarshalString(str, t);
    QString r = QString::fromUcs2((const ushort*)t.c_str());
    return r;
}
String ^ QtToSystemString( QString * str)
{

    wchar_t * wcar = (wchar_t *)str->ucs2();
    String^ r = gcnew String(wcar);
    return r;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜