【问题标题】:Error when passing a 'system::string' to a function将“system::string”传递给函数时出错
【发布时间】:2013-03-01 22:59:43
【问题描述】:

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

无法将参数 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;
        }

    }

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

【问题讨论】:

  • 我从没想过会看到有人在同一个调用中使用 C++/CLI、STL POSIX 函数...
  • @Matteo : 是的,这太可恶了...
  • 这几乎就像我对 C++ 不太熟悉,因此需要寻求帮助!我很感激你可能笑了,但请可怜我吧!

标签: c++ string c++-cli


【解决方案1】:

您正在尝试将托管的 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;
}

【讨论】:

  • 谢谢,第二个例子完美运行。正如您可能猜到的那样,我对 C++ 的经验并不多(示例来自互联网!),所以这就是为什么事情有点混乱。
  • @DavidGard 意识到这里实际上有两种“语言”在起作用——C++ 和 C++/CLI,它是 .NET C++“语言绑定”。如果您使用 C++/CLI,我倾向于尝试尽可能多地使用 .NET 选项...
  • +1 第一个提到System::IO::Directory::Exists
  • 我慢慢意识到情况确实如此,但我希望我还有几个问题!谢谢。
【解决方案2】:

您正在尝试将 CLR 字符串转换为 STL 字符串以将其转换为 C 字符串以将其与 POSIX 仿真函数一起使用。为什么会出现这样的并发症?既然您使用的是 C++/CLI,请使用 System::IO::Directory::Exists

【讨论】:

    【解决方案3】:

    要完成这项工作,您需要将托管类型 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);
    

    【讨论】:

      猜你喜欢
      • 2020-06-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-13
      相关资源
      最近更新 更多