Dot-Net

如何將 System::String^ 轉換為 std::string?

  • June 6, 2016

所以我在 clr 工作,在 Visual C++ 中創建 .net dll。

我相信這樣的程式碼:

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

具有通常會響應 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);
   }
...

但是當我嘗試編譯時它給了我 C4996

錯誤 C4996: ‘msclr::interop::error_reporting_helper<_To_Type,_From_Type>::marshal_as’: 庫不支持此轉換或不包含此轉換所需的標頭檔。請參閱有關“如何:擴展編組庫”的文件以添加您自己的編組方法。

該怎麼辦?

如果您使用的是 VS2008 或更新版本,您可以通過添加到 C++ 的自動編組非常簡單地做到這一點。例如,您可以將 from 轉換System::String^std::stringvia marshal_as

System::String^ clrString = "CLR string";
std::string stdString = marshal_as&lt;std::string&gt;(clrString);

這與用於 P/Invoke 呼叫的封送處理相同。

從文章如何將 System::String^ 轉換為MSDN 上的 std::string 或 std::wstring :

void MarshalString (String ^ s, string& os) 
{
   using namespace Runtime::InteropServices;
   const char* chars = 
     (const char*)(Marshal::StringToHGlobalAnsi(s)).ToPointer();
   os = chars;
   Marshal::FreeHGlobal(IntPtr((void*)chars));
}

用法:

std::string a;
System::String^ yourString = gcnew System::String("Foo");
MarshalString(yourString, a);
std::cout &lt;&lt; a &lt;&lt; std::endl; // Prints "Foo"

引用自:https://stackoverflow.com/questions/3539334