2010-09-07 12 views
5

to "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 
    } 
}; 

Ten kod gdy skompilowany z VS2008 daje:marshal_as, sznurki i pola vs. właściwości

.\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 ^)' 

Ale kiedy zmienić pole do własności:

następnie ten kod kompiluje bez błędów. Czemu?

Odpowiedz

5

Błąd, poprawiony w VS2010. Wyślij opinię item is here.

+2

Wygląda na to, że nie został naprawiony w VS2010 (przynajmniej nie działał w moim kodzie), ale obejście zostało rozwiązane. Dzięki! – Paul

+0

Nie działa również w moim kodzie, ale to obejście również naprawiono. Dzięki! – casper

+0

Rzeczywiście, jeszcze nie naprawiono i dzieje się to w innych sytuacjach, takich jak elementy zarządzanych tablic marszałkowych: marshal_as (arrayOfSystemStrings [i]). Obejście problemu polega na utworzeniu obojętnej zmiennej pośredniej: System :: String^manmy = arrayOfSystemStrings [i]; std :: string s = marshal_as (manekin); – Pragmateek

6

Rozwiązaniem jest zrobić kopię takiego:

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

Właśnie natknąłem się na to z VS2013.3 - nadal wydaje się być problem. Opisane obejście nadal działa. – Niall

1

Używam tego urywek dużo, a to za dużo bałaganu zadeklarować nową zmienną. Jednak to też działa:

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

Inną opcją, która działa dla mnie, jest ten mały szablon. Nie tylko rozwiązuje problem omawianego tu błędu, ale także naprawia inną rzecz, która jest zepsuta przez marshal_as, a mianowicie, że nie działa dla wejścia nullptr. Ale właściwie dobrym tłumaczeniem C++ dla nullptr System :: String byłoby .empty() std :: string(). Oto szablon:

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