Visual C++/CLI中std::int转System::String^使用marshal_as报错求助
解决C++/CLI中int转System::String^的marshal_as错误问题
这个错误是因为marshal_as默认不支持直接将原生int转换为System::String^,而且你缺少了必要的头文件来启用数值类型的托管转换。下面给你两种可行的解决方案:
方法一:使用托管类自带的转换方法(推荐)
最简洁的方式是直接利用.NET框架自带的转换函数,不需要引入interop库,代码更直观:
int count = 1; // 两种写法任选其一 System::String^ Apple = count.ToString(); // 或者 System::String^ Apple = System::Convert::ToString(count);
这种方式不仅代码量少,而且不需要额外的头文件依赖,是C++/CLI中数值转字符串的常用做法。
方法二:正确使用marshal_as(需要上下文和头文件)
如果你坚持要用marshal_as,需要补充包含对应的转换头文件,并且借助marshal_context来完成转换(因为这类转换需要临时内存管理):
// 必须包含这两个头文件 #include <msclr\marshal.h> #include <msclr\marshal_cppstd.h> using namespace msclr::interop; int count = 1; System::String^ Apple; // 创建转换上下文 marshal_context context; Apple = context.marshal_as<System::String^>(count);
你之前的代码只包含了基础的marshal.h,缺少marshal_cppstd.h来提供数值到托管字符串的转换模板,同时没有使用marshal_context,这才导致了不支持转换的错误。
内容的提问来源于stack exchange,提问作者Gaming
相关产品推荐
相关产品推荐

