1

我有以下函数,希望能告诉我文件夹是否存在,但是当我调用它时,我得到了这个错误 -

无法将参数 1 从 'System::String ^' 转换为 '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;
        }

    }

有人能告诉我如何解决这个问题吗?谢谢。

4

3 回答 3

2

您正在尝试将托管的 C++/CLI 字符串 ( System::String^) 转换为std::string. 没有为此提供隐式转换。

为了使其工作,您必须自己处理字符串转换

这可能看起来像:

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;
}
于 2013-03-01T23:02:38.940 回答
1

您正在尝试将 CLR 字符串转换为 STL 字符串以将其转换为 C 字符串以将其与 POSIX 仿真函数一起使用。为什么会出现这样的并发症?由于您无论如何都在使用 C++/CLI,因此只需使用System::IO::Directory::Exists.

于 2013-03-01T23:03:48.580 回答
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);
于 2013-03-01T23:03:11.450 回答