marshal_as、字符串和字段与属性
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;
那么这段代码编译时没有错误。为什么?
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
}
};
This code when compiled with VS2008 gives:
.\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 ^)'
But when I change the field into property:
property System::String^ text;
then this code compiles without errors. Why?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
解决方法是制作如下副本:
A workaround is to make a copy like this:
Bug,在VS2010中修复。反馈项目 在这里。
Bug, fixed in VS2010. Feedback item is here.
我经常使用这个片段,声明一个新变量太混乱了。然而这也有效:
另一个对我有用的选择是这个小模板。它不仅解决了这里讨论的错误,还修复了 marshal_as 损坏的另一个问题,即它不适用于 nullptr 输入。但实际上 nullptr System::String 的一个很好的 C++ 翻译是 .empty() std::string()。这是模板:
I'm using this snippet a lot, and it's too much clutter to declare a new variable. However this works too:
Another option that works for me is this little template. Not only does it solve the bug discussed here, it also fixes another thing that's broken with marshal_as, namely that it does not work for nullptr input. But actually a good c++ translation for a nullptr System::String would be an .empty() std::string(). Here is the template: