2010-09-07 113 views
5

包括 “stdafx.h中”

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

ref class Test { 
    System::String^ text; 
    void Method() { 
     std::string f = msclr::interop::marshal_as<std::string>(text); // line 8 
    } 
}; 

当VS2008编译该代码给出:marshal_as,字符串和领域对性能

.\test.cpp(8) : error C2665: 'msclr::interop::marshal_as' : none of the 3 overloads could convert all the argument types 
     f:\programy\vs9\vc\include\msclr\marshal.h(153): could be '_To_Type msclr::interop::marshal_as<std::string>(const char [])' 
     with 
     [ 
      _To_Type=std::string 
     ] 
     f:\programy\vs9\vc\include\msclr\marshal.h(160): or  '_To_Type msclr::interop::marshal_as<std::string>(const wchar_t [])' 
     with 
     [ 
      _To_Type=std::string 
     ] 
     f:\Programy\VS9\VC\include\msclr/marshal_cppstd.h(35): or  'std::string msclr::interop::marshal_as<std::string,System::String^>(System::String ^const &)' 
     while trying to match the argument list '(System::String ^)' 

但是,当我改变字段为属性:

property System::String^ text; 

然后这段代码编译没有错误。为什么?

回答

5

错误,在VS2010中修复。反馈意见项目is here

+2

在VS2010中似乎没有修复(至少,它没有在我的代码中工作),但解决方法为我工作。谢谢! – Paul 2011-03-16 19:55:53

+0

在我的代码中也没有工作,但是这个解决方法也修复了我的问题。谢谢! – casper 2013-02-08 11:54:55

+0

的确,尚未修复,并发生在其他情况下,例如托管数组元素编组:marshal_as (arrayOfSystemStrings [i])。解决方法是创建一个虚拟中间变量:System :: String^dummy = arrayOfSystemStrings [i]; std :: string s = marshal_as (dummy); – Pragmateek 2013-03-02 23:35:08

6

一种解决方法是让这样的副本:

ref class Test { 
    System::String^ text; 
    void Method() { 
     System::String^ workaround = text; 
     std::string f = msclr::interop::marshal_as<std::string>(workaround); 
    } 
}; 
+2

我刚刚遇到VS2013.3 - 仍然是一个问题。您描述的解决方法仍然有效。 – Niall 2014-11-12 08:11:01

1

我用这个片段了很多,这太过分了杂波声明一个新的变量。然而,这也可以工作:

msclr::interop::marshal_as<std::string>(gcnew String(string_to_be_converted)) 

另一个适用于我的选项是这个小模板。它不仅解决了这里讨论的错误,还修复了marshal_as中的另一件事情,即它不适用于nullptr输入。但实际上,nullptr System :: String的一个很好的C++翻译将是一个.empty()std :: string()。这里是模板:

template<typename ToType, typename FromType> 
inline ToType frum_cast(FromType s) 
{ 
    if (s == nullptr) 
     return ToType(); 
    return msclr::interop::marshal_as<ToType>(s); 
}