2013-03-01 32 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

相关问题