2010-08-21 458 views
6

所以我在clr工作,在visual C++中創建.net dll。如何將System :: String ^轉換爲std :: string?

我TRU這樣的代碼:

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

具有編碼器,其normaly resives的std :: string。但在這裏編譯器(Visual Studio)給我C2664錯誤,如果我從std :: string和通常相同的C2440去掉參數。 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 ::互操作:: error_reporting_helper < _To_Type,_From_Type> :: marshal_as':庫不支持此轉換,或不包含此轉換所需的頭文件。請參閱「如何:擴展編組庫」文檔以添加自己的編組方法。

該怎麼辦?

+4

你已經包含'msclr \ marshal.h'。試試'msclr \ marshal_cppstd.h'。 – 2010-08-21 23:14:58

+0

@Chris Schmich:謝謝 - 現在它編譯完美=) – Rella 2010-08-21 23:18:25

回答

6

如果您使用的是VS2008或更新的版本,您可以使用automatic marshaling added to C++進行簡單操作。例如,您可以通過marshal_asSystem::String^轉換爲std::string

System::String^ clrString = "CLR string"; 
std::string stdString = marshal_as<std::string>(clrString); 

這是用於P中的相同編組/ Invoke調用。

+0

我喜歡主意,但如何在我的代碼中聲明marshal_as?在哪裏和我寫什麼來聲明它(擺脫錯誤C2065),我使用VS2008 – Rella 2010-08-21 23:03:51

+1

要從'System :: String ^'轉到'std :: string',你需要'#include '聲明'marshal_as'。 – 2010-08-21 23:06:59

+0

當我嘗試#include 它給我致命錯誤C1083 ...所以我編輯了代碼並將其發佈在問題中(我使用他們在MS MSDN示例中使用的內容)...你可以看看它請。 – Rella 2010-08-21 23:14:01

4

從文章How to convert System::String^ to std::string or std::wstring MSDN上:

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 << a << std::endl; // Prints "Foo" 
3

您需要包括marshal_cppstd.h將字符串轉換^到的std :: string。

你沒有提到你是否關心非ASCII字符。 如果你需要unicode(如果沒有,爲什麼不!),有一個marshal_as返回一個std :: wstring。

如果你使用的是utf8,你將不得不推出自己的。你可以使用一個簡單的循環:

System::String^ s = ...; 
std::string utf8; 
for each(System::Char c in s) 
    // append encoding of c to "utf8"; 
相關問題