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

Rel*_*lla 7 .net c++ string visual-studio visual-c++

所以我在clr中工作,在visual c ++中创建.net dll.

我这样的代码:

 static bool InitFile(System::String^ fileName, System::String^ container)
{
    return enc.InitFile(std::string(fileName), std::string(container));
}
Run Code Online (Sandbox Code Playgroud)

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

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

更新:

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

#include <msclr\marshal.h>
#include <stdlib.h>
#include <string.h>
using namespace msclr::interop;
namespace NSSTW
{
  public ref class CFEW
  {
 public:
     CFEW() {}

     static System::String^ echo(System::String^ stringToReturn)
    {
        return stringToReturn;  
    }

     static bool InitFile(System::String^ fileName, System::String^ container)
    {   
        std::string sys_fileName = marshal_as<std::string>(fileName);;
        std::string sys_container = marshal_as<std::string>(container);;
        return enc.InitFile(sys_fileName, sys_container);
    }
...
Run Code Online (Sandbox Code Playgroud)

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

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

该怎么办?

Chr*_*ich 7

如果您使用的是VS2008或更新版本,您可以通过添加到C++自动编组功能非常简单地完成此操作.例如,您可以转换System::String^std::stringvia marshal_as:

System::String^ clrString = "CLR string";
std::string stdString = marshal_as<std::string>(clrString);
Run Code Online (Sandbox Code Playgroud)

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