.net – 如何将System :: String ^转换为std :: string?

前端之家收集整理的这篇文章主要介绍了.net – 如何将System :: String ^转换为std :: string?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
所以我在clr中工作,在visual c中创建.net dll.

我这样的代码

  1. static bool InitFile(System::String^ fileName,System::String^ container)
  2. {
  3. return enc.InitFile(std::string(fileName),std::string(container));
  4. }

有编码器,normaly resives std :: string.但是如果我从std :: string和C2440中删除通常相同的参数,那么编译器(visual studio)会给出C2664错误. VS告诉我它无法将System :: String ^转换为std :: string.

所以我很伤心……我该怎么做才能将System :: String ^变成std :: string?

更新:

现在有了你的帮助,我有了这样的代码

  1. #include <msclr\marshal.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. using namespace msclr::interop;
  5. namespace NSSTW
  6. {
  7. public ref class CFEW
  8. {
  9. public:
  10. CFEW() {}
  11.  
  12. static System::String^ echo(System::String^ stringToReturn)
  13. {
  14. return stringToReturn;
  15. }
  16.  
  17. static bool InitFile(System::String^ fileName,System::String^ container)
  18. {
  19. std::string sys_fileName = marshal_as<std::string>(fileName);;
  20. std::string sys_container = marshal_as<std::string>(container);;
  21. return enc.InitFile(sys_fileName,sys_container);
  22. }
  23. ...

但是当我尝试编译时,它给了我C4996

错误C4996:’msclr :: interop :: error_reporting_helper< _To_Type,_From_Type> :: marshal_as’:库不支持此转换,或者不包括此转换所需的头文件.有关添加自己的编组方法的信息,请参阅“如何:扩展封送库”的文档.

该怎么办?

解决方法

如果您使用的是VS2008或更新版本,则可以使用 automatic marshaling added to C++非常简单地执行此操作.例如,您可以通过 marshal_as将System :: String ^转换为std :: string:
  1. System::String^ clrString = "CLR string";
  2. std::string stdString = marshal_as<std::string>(clrString);

这与用于P / Invoke调用的编组相同.

猜你在找的C&C++相关文章