【问题标题】:Passing a string in Process::Start在 Process::Start 中传递字符串
【发布时间】:2014-02-27 19:59:43
【问题描述】:

我运行成功:

Process::Start("C:\\Users\\Demetres\\Desktop\\JoypadCodesApplication.exe");

来自 Windows 窗体应用程序 (visual c++),正如预期的那样,我有 2 个程序同时运行。我的问题是:

我可以将一个字符串 - 指示文件名 - 传递给 Process::Start 方法吗?我试过了:

std::string str="C:\\Users\\Demetres\\Desktop\\JoypadCodesApplication.exe";
Process::Start("%s", str);

但是失败了。这可能吗?

编辑:

【问题讨论】:

  • 这是几十个问题的重复:how to convert std::string to System::String^

标签: c++ .net string c++-cli process.start


【解决方案1】:

我认为您实际上需要编组到 System::String^ 以传递参数。 您甚至可以直接从 std::string 编组到 System::String^

///marshal_as<type>(to_marshal)
///marshal_context ctx; ctx.marshal_as<const char *>(to_marshal)
#include <msclr/marshal.h>
#include <msclr/marshal_cppstd.h>
#include <msclr/marshal_atl.h>
using namespace msclr::interop;
using namespace System::Runtime::InteropServices;

Process::Start(marshal_as<String^>(str));

但在这种情况下,您可以改用String^

String^ str = L"path to file";
Process::Start(str);

当您使用 C++/CLI 时,您要么需要来回编组,要么从一开始就使用正确的数据类型来决定如何使用它。

MSDN: Overview of Marshaling in C++

【讨论】:

    【解决方案2】:

    Process::Start 需要 String^,而您正试图将 std::string 传递给它。它没有可变参数版本,也不知道std::string 是什么。要从 std::string 传递值,您必须对其进行编组:

    std::string str("Some Path");
    Process::Start(marshal_as<String^>(str));
    

    【讨论】:

    • 不太可能,它仍然给我一个错误,如图所示。在我看来,故障实际上并不存在。
    • @dempap 不,错误就在那里(不过我确实忘记了编组问题)。
    猜你喜欢
    • 2018-11-02
    • 1970-01-01
    • 2016-12-18
    • 2022-01-25
    • 1970-01-01
    • 2015-08-04
    • 1970-01-01
    • 1970-01-01
    • 2017-11-19
    相关资源
    最近更新 更多