1

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?

3 Answers 3

6

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());

1
  • upvote! I tried this but didn't pass that length so, the compiler couldn't resolve which constructor to use! But yes, this works! Nov 18, 2011 at 5:27
3

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.

1
  • I'm accepting this answer as marshal_as function seems to convert _bstr_t without much cast and intermediate conversions. But Including a file is still a pain. I already have the namespace System::Runtime::InteropServices added and am using several functions from it, so I thought using Marshal::PtrToStringBSTR may be suitable for me for sake of uniformity. Kindly check the answer I posted and please tell me whether its a right way. Nov 18, 2011 at 5:25
0

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.