【问题标题】:Initialise System::String^ with literal but not string::c_str() or char[]用文字初始化 System::String^,但不是 string::c_str() 或 char[]
【发布时间】:2012-01-27 01:16:19
【问题描述】:

我最近开始学习 .net 和 Windows API,目前正在编写一个讨论串行端口的课程。

为了向串口写入一行,我使用了WriteLine 函数,它带有一个参数System::String^。我想知道是否可以从std::string 初始化System::String^

我注意到我可以执行以下操作:

serialPort->WriteLine("stuff");

但我做不到:

std::string data = "stuff";
serialPort->WriteLine(data.c_str());

另外,我做不到:

char data[] = "stuff";
serialPort->WriteLine(data);

也没有

char* data = "stuff";
serialPort->WriteLine(data);

谁能告诉我这里发生了什么?当我传入时,VS 是否以某种方式将文字转换为它自己的东西?

最后,我不确定我是否为此选择了正确的标签,因为我真的不知道它属于什么。

【问题讨论】:

  • 您正在尝试将 .NET 的内容与 C 和 C++ 的内容混合在一起,结果并不总是那么好。 .NET String 类型 notstd::stringchar 数组相同,它们不可相互转换。您应该使用您正在调用的函数所期望的任何类型。
  • 可以const char data[] = "stuff"; WriteLine(data)吗?
  • 您是否尝试过使用 gcnew 使用 data.c_str() 构建 System::String^? This answer 可能会起作用(根据需要将 const char* 替换为 std::string 和 c_str() )。
  • 不,这也不起作用。

标签: c++ .net string c++-cli console.writeline


【解决方案1】:

您始终可以使用字符串文字调用函数,因为编译器会自动将其转换为适当字符串类型的值。

这里的问题是您试图将 .NET Framework 的内容 (System::String) 与标准 C++ 字符串类型 (std::string) 混合在一起,但它们根本不能很好地混合。接受System::String 类型参数的.NET 函数没有被编写或重载以接受std::string 类型的参数。如果您使用的是 .NET Framework,那么您使用的是 C++/CLI,并且通常希望您使用 .NET 字符串类型,而不是 C++ 字符串类型。

类似地,标准 C++ 函数需要 std::string,并且对 .NET Framework 字符串类型一无所知。所以如果你希望调用 C++ 标准库中的函数,你应该使用它的字符串类型。

C 风格的字符串 (char[]) 是旧的后备,不是您在编写 C++ 代码时真正想要使用的东西。 std::string 始终是一个更好的选择,它甚至提供了 c_str() 方法,您已经知道在调用需要 char 数组的 API 函数时要使用该方法。但与其他两种字符串类型一样,这一种也不能相互转换。

您会遇到的一个特别大的问题是 std::stringchar[] 类型仅接受“窄”(非 Unicode)字符串,而 .NET Framework System::String 类型仅适用于宽(Unicode ) 字符串。在转换方面,这会进一步影响组合。不可能像演员表那样简单。

但这并不意味着在类型之间进行转换是不可能的。 MSDN 上有一个有用的文档解释了how to convert between various C++ string types

总而言之,您可以使用接受char* 的适当重载构造函数将C 样式字符串转换为System::String

const char* cString = "Hello, World!";
System::String ^netString = gcnew System::String(cString);
Console::WriteLine(netString);
delete netString;

然后,当然,您可以将上述方法与c_str() 方法相结合,将std::string 转换为System::String

std::string stdString("Hello, World!");
System::String ^netString = gcnew System::String(stdString.c_str());
Console::WriteLine(netString);
delete netString;

【讨论】:

    猜你喜欢
    • 2010-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-27
    • 2018-06-04
    • 2019-01-14
    • 1970-01-01
    相关资源
    最近更新 更多