Pregunta

Firstly, I'm some what new to C++/CLI.

After doing some research I've found that I can use Marshal::PtrToStringBSTR to convert an IntPtr to System::String. So, is there a way to convert my _bstr_t variable to an IntPtr so that I can pass it to the function mentioned and do conversion?

Or,

What is the correct way of converting a _bstr_t variable to System::String?

¿Fue útil?

Solución

You should be able to use marshal_as to get a System::String.

marshal_as<System::String^>(value);

Here's the MSDN page for the different string types: http://msdn.microsoft.com/en-us/library/bb384865.aspx

Most important thing is to pay attention to the right #include depending on your string type.

Otros consejos

System::String has a constructor that takes a wchar_t*. Which makes this code work:

_bstr_t bs(L"Hello world");
String^ ss = gcnew String(bs.GetBSTR(), 0, bs.length());

Passing the length() ensures that embedded zeros are properly handled. If you don't care about that then you can simply use gcnew String(bs.GetBSTR());

I managed to find a solution through the way I mentioned itself, by using Marshal::PtrToStringBSTR. This is what I did:

void SomeFunction( String^% str )
{
    _bstr_t bs(L"Hello world");
    str = Marshal::PtrToStringBSTR(
          static_cast<IntPtr>( bs.GetAddress()));
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top