1

首先,我对C++/CLI有点陌生。

在做了一些研究之后,我发现我可以使用Marshal::PtrToStringBSTR将一个转换IntPtrSystem::String. 那么,有没有办法将我的_bstr_t变量转换为一个IntPtr,以便我可以将它传递给提到的函数并进行转换?

或者,

_bstr_t将变量转换为的正确方法是System::String什么?

4

3 回答 3

6

System::String 有一个带有 wchar_t* 的构造函数。这使得这段代码工作:

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

传递 length() 可确保正确处理嵌入的零。如果你不关心,那么你可以简单地使用 gcnew String(bs.GetBSTR());

于 2011-11-17T15:36:14.983 回答
3

您应该可以marshal_as使用System::String.

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

这是不同字符串类型的 MSDN 页面:http: //msdn.microsoft.com/en-us/library/bb384865.aspx

最重要的是根据您的字符串类型注意正确的#include。

于 2011-11-17T15:07:22.520 回答
0

我设法通过我自己提到的方式找到了解决方案,使用Marshal::PtrToStringBSTR. 这就是我所做的:

void SomeFunction( String^% str )
{
    _bstr_t bs(L"Hello world");
    str = Marshal::PtrToStringBSTR(
          static_cast<IntPtr>( bs.GetAddress()));
}
于 2011-11-18T05:21:08.253 回答