marshal_as,字符串和字段与属性

问题描述 投票:5回答:3

include "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编译时此代码给出:

.\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;

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

visual-studio-2008 c++-cli marshalling
3个回答
5
投票

错误,已在VS2010中修复。反馈项is here


6
投票

解决方法是制作这样的副本:

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

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);
}
© www.soinside.com 2019 - 2024. All rights reserved.