2013-03-01 53 views
1

我有以下的功能,相信能告訴我一個文件夾是否存在,但是當我把它,我得到這個錯誤 -錯誤傳遞「系統::字符串」的功能時

無法從 '系統字符串^ ::' 轉換參數1 '的std :: string'

功能 -

#include <sys/stat.h> 
#include <string> 

bool directory_exists(std::string path){ 

    struct stat fileinfo; 

    return !stat(path.c_str(), &fileinfo); 

} 

調用(從持有形式,其中form.h文件用戶選擇文件夾) -

private: 
    System::Void radioListFiles_CheckedChanged(System::Object^ sender, System::EventArgs^ e) { 

     if(directory_exists(txtActionFolder->Text)){     
      this->btnFinish->Enabled = true; 
     } 

    } 

是否有人能告訴我如何filx這?謝謝。

+3

我從來沒有希望看到任何人在同一個調用中使用C++/CLI,STL *和* POSIX函數... – 2013-03-01 23:00:48

+1

@Matteo:是的,這是相當可憎的... – ildjarn 2013-03-01 23:05:54

+0

這幾乎就像我不是很用C++過期,因此需要尋求幫助!我贊成你可能有一個笑,但有一些可惜我! – 2013-03-01 23:15:42

回答

2

您試圖從託管的C++/CLI字符串(System::String^)轉換爲std::string。沒有爲此提供隱式轉換。

爲了這個工作,你必須處理string conversion yourself

這可能會是這個樣子:

std::string path = context->marshal_as<std::string>(txtActionFolder->Text)); 
if(directory_exists(path)) { 
    this->btnFinish->Enabled = true; 
} 

話雖這麼說,在這種情況下,它可能是更容易堅持,託管API完全:

if(System::IO::Directory::Exists(txtActionFolder->Text)) { 
    this->btnFinish->Enabled = true; 
} 
+0

謝謝,第二個例子完美工作。正如你可能猜到的那樣,我不是用C++(來自互聯網的例子!)來展示的,所以這就是事情有點混亂的原因。 – 2013-03-01 23:14:10

+2

@DavidGard意識到這裏真的有兩種「語言」--C++和C++/CLI,它是.NET C++「語言綁定」。如果您使用的是C++/CLI,我傾向於嘗試儘可能多地使用.NET選項... – 2013-03-01 23:15:05

+0

+1是第一個提及'System :: IO :: Directory :: Exists'的人。 – ildjarn 2013-03-01 23:15:08

0

爲了使這項工作,你需要將託管類型System::String轉換爲本機類型std::string。這涉及到一些編組,並將導致2個單獨的字符串實例。 MSDN有一個方便的表中各種不同類型的編組字符串

http://msdn.microsoft.com/en-us/library/bb384865.aspx

在這種特殊情況下,你可以做以下

std::string nativeStr = msclr::interop::marshal_as<std::string>(managedStr); 
1

您正在嘗試轉換將CLR字符串轉換爲STL字符串以將其轉換爲C字符串以與POSIX仿真功能一起使用。爲什麼這麼複雜?由於您正在使用C++/CLI,只需使用System::IO::Directory::Exists即可。

+0

謝謝,以及下面的例子,工作。 – 2013-03-01 23:16:21